//Endorsement.ascx - ddlPremiumType event handler to
//enable/disable txtPremium control
//chogue 11/2/10
function HandlePremiumTypeSelectedIndexChanged() {
    if ($("select[id$='ddlPremiumType'] :selected").val() == "SystemCalculated") {
        $('.disable_textbox input').attr('disabled', true); 
    }
    else {
        $('.disable_textbox input').removeAttr('disabled');
    }
}

function loadjsfile(filename)
{
    var fileref = document.createElement('script')
    fileref.setAttribute("type", "text/javascript")
    fileref.setAttribute("src", filename)
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}
//global street address variable
//chogue pre-fill address on tabs issue
var streetAddress = null;
//global city address variable
//chogue pre-fill address on tabs issue
var cityAddress = null;

function SetStreetAddress(address)
{
    if (!(address == undefined))
    {
        streetAddress = address;
    }
}

//pre-fill the street address
//chogue pre-fill address on tabs issue
function LoadStreetAddress() {
    //streetAddress must be defined
    if (!(streetAddress == undefined))
    {
        //1.the property must exist
        //2.the property must be empty
        //3.the property must be enabled
        //4.the button text must say "Get coverages"
        if ($("*[propname$='STREET_ADDRESS']").length > 0 &&
            $("*[propname$='STREET_ADDRESS']").val().length == 0 &&
            $("*[propname$='STREET_ADDRESS']").attr('disabled') != true &&
            $("input[id$='btnGetCoverages']").val() == "Get coverages")
        {

            $("*[propname$='STREET_ADDRESS']").val(streetAddress);
        }
    }
}

function SetCityAddress(city)
{
    if (!(city == undefined))
    {
        cityAddress = city;
    }
}

//pre-fill the city address
//chogue pre-fill address on tabs issue
function LoadCityAddress()
{
    //cityAddress must be defined
    if (!(cityAddress == undefined))
    {
        //1.the property must exist
        //2.the property must be empty
        //3.the property must be enabled
        //4.the button text must say "Get coverages"
        if ($("*[propname$='CITY']").length > 0 &&
            $("*[propname$='CITY']").val().length == 0 &&
            $("*[propname$='CITY']").attr('disabled') != true &&
            $("input[id$='btnGetCoverages']").val() == "Get coverages")
        {
            $("*[propname$='CITY']").val(cityAddress);
        }
    }
}

function BindPickerControls(urllevels)
{
    if ($("*[id$='txtClassCode']").is(":disabled"))
    {
        $(".toggle-button").hide();
    } else
    {
        // get data for the ClassCodeSelector autocomplete control.
        // '9999' tells control not to hit webservice, used on page load.
        LoadClassCodeSelectorAutocomplete(urllevels);
    }

    if ($("*[id$='txtISOTerrCode']").is(":enabled"))
    {
        // get data for the TerritoryCodeSelector autocomplete control.
        // false as first parameter tells control not to hit webservice, used on page load.
        GetTerritoryListData(false, false, urllevels);
    }

    var urlprefix = "";
    var i;
    for (i = 0; i < urllevels; i++)
    {
        urlprefix += "../";
    }

    // logic for toggle button for filter div on ClassCodeSelector control.
    $(".toggle-button").click(function()
    {
        if ($(".toggleable").is(":hidden"))
        {
            $(".toggleable").show('fast');
            $(this).attr('src', urlprefix + 'images/minus.gif');
            $.fn.ClassCodeSelectorAutocomplete.CollectIDsFromClassCodeFilter();
        }
        else
        {
            $(".toggleable").hide('fast');
            $(this).attr('src', urlprefix + 'images/plus.gif');
            $.fn.ClassCodeSelectorAutocomplete.HideResults();
        }

        if (cc_ResultsCurrentlyShown)
        {
            $.fn.ClassCodeSelectorAutocomplete.ShowResults();
        }
    });

    // this will hide the results and filter if another tab is clicked.
    $(".MenuTabItem").click(function() {
        if (cc_ResultsCurrentlyShown) {
            $.fn.ClassCodeSelectorAutocomplete.HideResults();
        }
        $(".toggleable").hide('fast');
        $(".toggle-button").attr('src', urlprefix + 'images/plus.gif');
    });
}

function createCSSRef(url)
{
    var obj = document.createElement("link");
    obj["href"] = url;
    obj["rel"] = "stylesheet";
    obj["type"] = "text/css";
    return obj;
}
function toggleDocumentCheckBox(currentdoc, caller_name, select_all_box_name, select_all_link_name)
{
    //var select_all_box = currentdoc.getElementById("ckbx_select_all_documents");
    //var select_all_link = currentdoc.getElementById("btn_select_all_documents");
    
    var select_all_box = $("input[id$='" + select_all_box_name + "']"); 
    var select_all_link = $("a[id$='" + select_all_link_name + "']");
    var caller = $("input[id$='" + caller_name + "']");
    
    //alert("value = " + select_all_link[0].value);
    //alert("innerHTML = " + select_all_link[0].innerHTML);
    //alert("select_all_box[0].checked = " + select_all_box[0].checked);
    
    
    if (select_all_box[0] != null)
    {
        if (caller[0] != select_all_box[0])
        {    
            if (select_all_box[0].checked == false)
            {
                select_all_box[0].checked = true;
                select_all_link[0].innerHTML = "Click Here to Select None";
            } 
            else
            {
                select_all_box[0].checked = false;
                select_all_link[0].innerHTML = "Click Here to Select All";
            }
        }
        else
        {
            if (select_all_box[0].checked == false)
            {
                //select_all_box[0].checked = true;
                select_all_link[0].innerHTML = "Click Here to Select All";
            } 
            else
            {
                //select_all_box[0].checked = false;
                select_all_link[0].innerHTML = "Click Here to Select None";
            }        
        }
    }
    if (select_all_box[0] != null)
    {
        var documentIDs = new Array();
        var docs = $("*[id$='chkReport']");
        for (var i = 0; i < docs.length; i++)
        {
            var e = docs[i];
            if (e.type == 'checkbox')
            {
                e.checked = select_all_box[0].checked;
            }
        }
    }
    return false;
}

function toggleCheckBoxesByAttribute(checkedState, attributeName, attributeValue, checkBoxID)
{
    var documentIDs = new Array();
    var listBox = $("*[id$='" + checkBoxID + "'][" + attributeName + "='" + attributeValue + "']");
    for (var i = 0; i < listBox.length; i++)
    {
        listBox[i].checked = checkedState;
    }
    return false;
}

function SelectAndUnselectAll(currentdoc, checkBoxName, selectAllCheckBox, gridViewName)
{
    //var inputs = currentdoc.getElementsByTagName(checkBoxName);
    //var inputs = $("input[id$='chkReport']");
    
    //alert("$(\"input[id$='" + checkBoxName + "']\")");
    
    var inputs = $("input[id$='" + checkBoxName + "']"); 
   
    //alert(inputs.length + " " + checkBoxName);
    
    if (selectAllCheckBox.checked == true)
    {
        //alert("selectAllCheckBox is checked");
        for (var iCount = 0; iCount < inputs.length; iCount++)
        {
            //alert("inLoop - " + inputs[iCount].name + " " + inputs[iCount].type);
            if (inputs[iCount].type == 'checkbox')
            {
               //alert("checking - " + inputs[iCount].name + " " + inputs[iCount].type);
               inputs[iCount].checked = true;
            }
        }

    } else
    {
        //alert("selectAllCheckBox is NOT checked");
        for (var iCount = 0; iCount < inputs.length; iCount++)
        {
            //alert("inLoop - " + inputs[iCount].name + " " + inputs[iCount].type);
            if (inputs[iCount].type == 'checkbox')
            {
                //alert("unchecking - " + inputs[iCount].name + " " + inputs[iCount].type);
                inputs[iCount].checked = false;
            }
        }

    }
}

function urlDecode(str)
{
    str = str.replace(new RegExp('\\+', 'g'), ' ');
    return unescape(str);
}
function urlEncode(str)
{
    str = escape(str);
    str = str.replace(new RegExp('\\+', 'g'), '%2B');
    return str.replace(new RegExp('%20', 'g'), '+');
}

var END_OF_INPUT = -1;

var base64Chars = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                            'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                            'w', 'x', 'y', 'z', '0', '1', '2', '3',
                            '4', '5', '6', '7', '8', '9', '+', '/');

var reverseBase64Chars = new Array();
for (var i = 0; i < base64Chars.length; i++)
{
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str)
{
    base64Str = str;
    base64Count = 0;
}

function readBase64()
{
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}

function encodeBase64(str)
{
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT)
    {
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[inBuffer[0] >> 2]);
        if (inBuffer[1] != END_OF_INPUT)
        {
            result += (base64Chars[((inBuffer[0] << 4) & 0x30) | (inBuffer[1] >> 4)]);
            if (inBuffer[2] != END_OF_INPUT)
            {
                result += (base64Chars[((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6)]);
                result += (base64Chars[inBuffer[2] & 0x3F]);
            } else
            {
                result += (base64Chars[((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else
        {
            result += (base64Chars[((inBuffer[0] << 4) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76)
        {
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}

function readReverseBase64()
{
    if (!base64Str) return END_OF_INPUT;
    while (true)
    {
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter])
        {
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
    return END_OF_INPUT;
}

function ntos(n)
{
    n = n.toString(16);
    if (n.length == 1) n = "0" + n;
    n = "%" + n;
    return unescape(n);
}

function decodeBase64(str)
{
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
           && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT)
    {
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff) | inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT)
        {
            result += ntos((((inBuffer[1] << 4) & 0xff) | inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT)
            {
                result += ntos((((inBuffer[2] << 6) & 0xff) | inBuffer[3]));
            } else
            {
                done = true;
            }
        } else
        {
            done = true;
        }
    }
    return result;
}

var digitArray = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
function toHex(n)
{
    var result = ''
    var start = true;
    for (var i = 32; i > 0; )
    {
        i -= 4;
        var digit = (n >> i) & 0xf;
        if (!start || digit != 0)
        {
            start = false;
            result += digitArray[digit];
        }
    }
    return (result == '' ? '0' : result);
}

function pad(str, len, pad)
{
    var result = str;
    for (var i = str.length; i < len; i++)
    {
        result = pad + result;
    }
    return result;
}

function encodeHex(str)
{
    var result = "";
    for (var i = 0; i < str.length; i++)
    {
        result += pad(toHex(str.charCodeAt(i) & 0xff), 2, '0');
    }
    return result;
}

var hexv = {
    "00": 0, "01": 1, "02": 2, "03": 3, "04": 4, "05": 5, "06": 6, "07": 7, "08": 8, "09": 9, "0A": 10, "0B": 11, "0C": 12, "0D": 13, "0E": 14, "0F": 15,
    "10": 16, "11": 17, "12": 18, "13": 19, "14": 20, "15": 21, "16": 22, "17": 23, "18": 24, "19": 25, "1A": 26, "1B": 27, "1C": 28, "1D": 29, "1E": 30, "1F": 31,
    "20": 32, "21": 33, "22": 34, "23": 35, "24": 36, "25": 37, "26": 38, "27": 39, "28": 40, "29": 41, "2A": 42, "2B": 43, "2C": 44, "2D": 45, "2E": 46, "2F": 47,
    "30": 48, "31": 49, "32": 50, "33": 51, "34": 52, "35": 53, "36": 54, "37": 55, "38": 56, "39": 57, "3A": 58, "3B": 59, "3C": 60, "3D": 61, "3E": 62, "3F": 63,
    "40": 64, "41": 65, "42": 66, "43": 67, "44": 68, "45": 69, "46": 70, "47": 71, "48": 72, "49": 73, "4A": 74, "4B": 75, "4C": 76, "4D": 77, "4E": 78, "4F": 79,
    "50": 80, "51": 81, "52": 82, "53": 83, "54": 84, "55": 85, "56": 86, "57": 87, "58": 88, "59": 89, "5A": 90, "5B": 91, "5C": 92, "5D": 93, "5E": 94, "5F": 95,
    "60": 96, "61": 97, "62": 98, "63": 99, "64": 100, "65": 101, "66": 102, "67": 103, "68": 104, "69": 105, "6A": 106, "6B": 107, "6C": 108, "6D": 109, "6E": 110, "6F": 111,
    "70": 112, "71": 113, "72": 114, "73": 115, "74": 116, "75": 117, "76": 118, "77": 119, "78": 120, "79": 121, "7A": 122, "7B": 123, "7C": 124, "7D": 125, "7E": 126, "7F": 127,
    "80": 128, "81": 129, "82": 130, "83": 131, "84": 132, "85": 133, "86": 134, "87": 135, "88": 136, "89": 137, "8A": 138, "8B": 139, "8C": 140, "8D": 141, "8E": 142, "8F": 143,
    "90": 144, "91": 145, "92": 146, "93": 147, "94": 148, "95": 149, "96": 150, "97": 151, "98": 152, "99": 153, "9A": 154, "9B": 155, "9C": 156, "9D": 157, "9E": 158, "9F": 159,
    "A0": 160, "A1": 161, "A2": 162, "A3": 163, "A4": 164, "A5": 165, "A6": 166, "A7": 167, "A8": 168, "A9": 169, "AA": 170, "AB": 171, "AC": 172, "AD": 173, "AE": 174, "AF": 175,
    "B0": 176, "B1": 177, "B2": 178, "B3": 179, "B4": 180, "B5": 181, "B6": 182, "B7": 183, "B8": 184, "B9": 185, "BA": 186, "BB": 187, "BC": 188, "BD": 189, "BE": 190, "BF": 191,
    "C0": 192, "C1": 193, "C2": 194, "C3": 195, "C4": 196, "C5": 197, "C6": 198, "C7": 199, "C8": 200, "C9": 201, "CA": 202, "CB": 203, "CC": 204, "CD": 205, "CE": 206, "CF": 207,
    "D0": 208, "D1": 209, "D2": 210, "D3": 211, "D4": 212, "D5": 213, "D6": 214, "D7": 215, "D8": 216, "D9": 217, "DA": 218, "DB": 219, "DC": 220, "DD": 221, "DE": 222, "DF": 223,
    "E0": 224, "E1": 225, "E2": 226, "E3": 227, "E4": 228, "E5": 229, "E6": 230, "E7": 231, "E8": 232, "E9": 233, "EA": 234, "EB": 235, "EC": 236, "ED": 237, "EE": 238, "EF": 239,
    "F0": 240, "F1": 241, "F2": 242, "F3": 243, "F4": 244, "F5": 245, "F6": 246, "F7": 247, "F8": 248, "F9": 249, "FA": 250, "FB": 251, "FC": 252, "FD": 253, "FE": 254, "FF": 255
};

function decodeHex(str)
{
    str = str.toUpperCase().replace(new RegExp("s/[^0-9A-Z]//g"));
    var result = "";
    var nextchar = "";
    for (var i = 0; i < str.length; i++)
    {
        nextchar += str.charAt(i);
        if (nextchar.length == 2)
        {
            result += ntos(hexv[nextchar]);
            nextchar = "";
        }
    }
    return result;
}

function printDocuments(URL)
{
    var documentIDs = new Array();
    var docs = document.getElementsByName("select_document_Checked");
    for (var i = 0; i < docs.length; i++)
    {
        var e = docs[i];
        if ((e.type == 'checkbox') && (e.checked == true))
        {
            documentIDs.push(e.value);
        }
    }
    if (documentIDs.length == 0)
    {
        alert('Please select a report');
    } else
    {
        var docids = documentIDs.join();
        var URLWithID = URL + "?x=" + encodeBase64(docids);
        window.open(URLWithID);
    }
    return false;
}

function PrintDocument(URL)
{
    var us = URL.PostBackUrl;
    window.open(us);
}

// USED BY CLASSCODE BUILDER AND TERRITORY BUILDER
function hideShow(objectName, onlyShow)
{
    var object = document.getElementById(objectName)
    if (object.style.display == '' && !onlyShow)
    {
        object.style.display = 'None';
        unhideSelect();
    } else
    {
        object.style.display = '';
        hideSelect();
    }
}

function selectValue(v, txtBox, div, descriptionDiv, description)
{
    var object = document.getElementById(txtBox)
    object.value = v;
}
// END CLASSCODE BUILDER AND TERRITORY BUILDER

// Hide all select boxes
function hideSelect()
{
    if (document.all)
    {
        for (formIdx = 0; formIdx < document.forms.length; formIdx++)
        {
            var theForm = document.forms[formIdx];
            for (elementIdx = 0; elementIdx < theForm.elements.length; elementIdx++)
            {
                window.status += theForm[elementIdx].type;
                if (theForm[elementIdx].type == "select-one")
                {
                    var controlName = theForm[elementIdx].name;
                    if (controlName.indexOf("classBuilder") == -1 /*&& controlName.indexOf("TerritoryBuilder")== -1*/)
                        theForm[elementIdx].style.visibility = "hidden";
                }
            }
        }
    }
}

// Unhide all select boxes
function unhideSelect()
{
    if (document.all)
    {
        for (formIdx = 0; formIdx < document.forms.length; formIdx++)
        {
            var theForm = document.forms[formIdx];
            for (elementIdx = 0; elementIdx < theForm.elements.length; elementIdx++)
            {
                if (theForm[elementIdx].type == "select-one")
                {
                    theForm[elementIdx].style.visibility = "visible";
                }
            }
        }
    }
}

/************************************************/
/************* common cookie functions ****************/
/*
name - name of the cookie
value - value of the cookie
[expires] - expiration date of the cookie
(defaults to end of current session)
[path] - path for which the cookie is valid
(defaults to path of calling document)
[domain] - domain for which the cookie is valid
(defaults to domain of calling document)
[secure] - Boolean value indicating if the cookie transmission requires
a secure transmission
* an argument defaults when it is assigned null as a placeholder
* a null placeholder is not required for trailing omitted arguments
*/
function setCookie(name, value, expires, path, domain, secure)
{
    var curCookie = name + "=" + escape(value) +
                    ((expires) ? "; expires=" + expires.toGMTString() : string.Empty) +
                    ((path) ? "; path=" + path : string.Empty) +
                    ((domain) ? "; domain=" + domain : string.Empty) +
                    ((secure) ? "; secure" : string.Empty);
    document.cookie = curCookie;
}


// name - name of the desired cookie
// return string containing value of specified cookie or null
//  if cookie does not exist
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
        begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
        end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

//name - name of the cookie
//[path] - path of the cookie (must be same as path used to create cookie)
//[domain] - domain of the cookie (must be same as domain used to create cookie)
//path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
                          ((path) ? "; path=" + path : string.Empty) +
                          ((domain) ? "; domain=" + domain : string.Empty) +
                          "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"
function fixDate(date)
{
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
}

function hideShowDiv(imageName, divName, hiddenControl)
{
    var currentSource = document.getElementById(imageName).src;
    var currentState = document.getElementById(hiddenControl); //1 = open; 0= closed
    if (currentState.value == "1")
    {
        //currently up.. visible
        document.getElementById(divName).style.display = "none";
        document.getElementById(imageName).src = '/images/down.gif';
        currentState.value = "0"

    } else
    {
        document.getElementById(divName).style.display = string.Empty;
        document.getElementById(imageName).src = '/images/up.gif';
        currentState.value = "1"

    }

}

function divOpenCloseWithImage(imageName, divName) {
    var src = ($("#"+imageName).attr("src") === "/images/collapse.jpg") ? "/images/expand.jpg" : "/images/collapse.jpg";
    $("#"+imageName).attr("src", src);
    $("#"+divName).slideToggle(300);
}

function updateScroll()
{
    try { document.getElementById("scrollValue").value = document.body.scrollTop; }
    catch (e) { }
}


function setScroll()
{
    try { document.body.scrollTop = document.getElementById("scrollValue").value; }
    catch (e) { }
}

function hideShowDropDownBox(dropDown)
{
    var selectedBox = document.getElementById(dropDown);
    var selectedValue = selectedBox.options[selectedBox.selectedIndex].value;
    var dropDownsToDisplay = selectedValue.split(';');

    for (var k = 0; k < dropDownsToDisplay.length; k++)
    {
        var obj = dropDownsToDisplay[k];
        document.getElementById(dropDownsToDisplay[k]).style.display = string.Empty;
    }
    hideShowAllChildren(dropDown, selectedBox.selectedIndex)
}

function hideShowAllChildren(dropDown, selectedIndex)
{
    var selectedBox;
    try { selectedBox = document.getElementById(dropDown); }
    catch (e) { return; }

    for (var i = 0; i < selectedBox.options.length; i++)
    {
        var selectedValue = selectedBox.options[i].value;
        var dropDownsToDisplay = selectedValue.split(';');

        for (var k = 0; k < dropDownsToDisplay.length; k++)
        {
            var obj = dropDownsToDisplay[k];

            //if it is not the selected index then we are going to hide the dropDown
            if (i == selectedIndex)
            {
                document.getElementById(dropDownsToDisplay[k]).style.display = string.Empty;
            } else
            {
                document.getElementById(dropDownsToDisplay[k]).style.display = "none";
            }

            try { hideShowAllChildren(dropDownsToDisplay[k], -1); }
            catch (e) { }
        }
    }
}

function isVinValid(vinControl, classCode, modelYear)
{
    var mYear = document.getElementById(modelYear).value
    validateVin(vinControl, classCode, mYear);
}

function Left(str, n)
{
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

function Right(str, n)
{
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
    {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

function IsTrailer(classCode)
{
    var firstChar = "";
    if (classCode.length == 5)
    {
        firstChar = Left(classCode, 1);
        if (firstChar == "6")
        {
            return true;
        } else
        {
            return false;
        }

    } else
    {
        return false;
    }
}

function IsLessThan1981(modelYear)
{
    if (modelYear != "")
    {
        if (parseInt(modelYear) < 1981)
        {
            return true;
        } else
        {
            return false;
        }
    } else
    {
        return false;
    }
}

function HideOrShowVehicleDetails() {
    //during bind, and issue, this code should not be enabling
    //controls, only disabling based on the Platetype setting 
    if ($("*[propname$='PLATETYPE']").attr("disabled") == true) {
        //This runs to make sure that the license plate box is on the UI
        if ($("*[propname$='LICENSE_PLATE']").length != 0) {
            //if the rating was based on plate rating disable the make, model, vin, year
            if ($("*[propname$='PLATETYPE']").val() != "N/A") {
                $("*[propname$='YEAR']").attr("disabled", true).val("").removeClass("rqdTextBox");             
                $("*[propname$='YEAR_RQD_IND']").hide();
                $("*[propname$='MAKE']").attr("disabled", true).val("").removeClass("rqdTextBox");
                $("*[propname$='MAKE_RQD_IND']").hide();
                $("*[propname$='MODEL']").attr("disabled", true).val("").removeClass("rqdTextBox");
                $("*[propname$='MODEL_RQD_IND']").hide();
                $("*[propname$='VIN']").attr("disabled", true).val("").removeClass("rqdTextBox");
                $("*[propname$='VIN_RQD_IND']").hide();
            } else {
                $("*[propname$='LICENSE_PLATE']").attr("disabled", true).val("").removeClass("rqdTextBox");
                $("*[propname$='LICENSE_PLATE_RQD_IND']").hide();
            }
        }
        
        return;
    }
    //This runs to make sure that the license plate box is on the UI and the UI is completely editable
    //It will disable and enable controls
    if ($("*[propname$='LICENSE_PLATE']").length != 0) {

        if ($("*[propname$='PLATETYPE']").val() == "N/A") {
            $("*[propname$='YEAR']").attr("disabled", false);
            $("*[propname$='MAKE']").attr("disabled", false);
            $("*[propname$='MODEL']").attr("disabled", false);
            $("*[propname$='VIN']").attr("disabled", false);
            $("*[propname$='LICENSE_PLATE']").attr("disabled", true).val("");

        } else {
            $("*[propname$='YEAR']").attr("disabled", true).val("");
            $("*[propname$='MAKE']").attr("disabled", true).val("");
            $("*[propname$='MODEL']").attr("disabled", true).val("");
            $("*[propname$='VIN']").attr("disabled", true).val("");
            $("*[propname$='LICENSE_PLATE']").attr("disabled", false);
        }
    }

}

function validateVin(vinControl, classCode, modelYear) {
    var vinText = document.getElementById(vinControl);
    INVALID = "Invalid VIN: ";
    // convert everything to uppercase
    InputString = vinText.value.toUpperCase();
    // If VIN blank no further processing
    if (InputString.length == 0)
        return true;
    if (IsLessThan1981(document.getElementById(modelYear).value))
        return true;
    if (IsTrailer(document.getElementById(classCode).value))
        return true;
    // remove leading spaces
    while (InputString.charAt(0) == ' ')
        InputString = InputString.substring(1);
    // remove trailing spaces
    while (InputString.charAt(InputString.length - 1) == ' ')
        InputString = InputString.substring(0, InputString.length - 1);
    // we only deal with 17 digit VIN's
    if (InputString.length < 17)
    {
        RQBIError(INVALID + 'VIN should be 17 characters long for motorized vehicles 1981 or later, please correct before policy issuance.');
        return false;
    }
    if (InputString.length > 17)
    {
        // should never get here
        RQBIError(INVALID + 'VIN should be 17 characters long for motorized vehicles 1981 or later, please correct before policy issuance.');
        return false;
    }

    // Verify the input string
    vin = "";
    for (var i = 0; i < 17; i++)
    {
        ccode = InputString.charCodeAt(i);
        cval = InputString.charAt(i);
        // Only chars 0-9 and A-Z are valid
        // but not Q. Further checking is done
        // later. We check unicode values.
        if (ccode == 81 || ccode < 48 || ccode > 90 || (ccode > 57 && ccode < 65))
        {
            //Error(INVALID + 'Character \'' + cval + '\' at index ' + (i + 1) + ' of VIN is incorrect');
            RQBIError(INVALID + 'Invalid VIN, please correct before policy issuance.');
            return false;
        }

        // We convert any letter 'O' into a zero '0'
        // and any letter 'I' into a one '1'.
        // This fixes possible user input errors
        if (cval == 'O')
            vin += "0";
        else if (cval == 'I')
            vin += "1";
        else
            vin += InputString.charAt(i);
    }

    // The checkdigit is the checksum of
    // the entire VIN for USA and Canada vehicles.
    checkDigit = vin.charAt(8);

    // RoW cars ignore the check digit.
    // it's always a 'Z' regardless
    RoW = true;
    if (checkDigit != 'Z')
    {
        CheckDigitVINValue = ChksumCheckDigit(vin);
        RoW = false;
    }

    // Validate the checkdigit
    if ("0123456789XZ".indexOf(checkDigit) < 0)
    {
        alert(INVALID + 'Invalid check digit character');
        return false;
    }

    // if not a Row, validate the checksum
    else if (RoW == false && CheckDigitVINValue == "error")
    {
        alert(INVALID + 'checksum failed');
        return false;
    }

    else if (RoW == false && CheckDigitVINValue != checkDigit)
    {
        alert(INVALID + 'check digit failed checksum');
        return false;
    }
    return true;
}

function PadDigits(txtBox, totalDigits)
{
    var object = document.getElementById(txtBox)
    var n = object.value;
    var pd = '';
    if (totalDigits > n.length)
    {
        for (i = 0; i < (totalDigits - n.length); i++)
        {
            pd += '0';
        }
    }
    object.value = pd + n.toString();
}


function PadYear(txtBox) {
    var object = document.getElementById(txtBox)
    if (!(object == undefined)) {
        var n = object.value;
        var pd = '19';
        if (n.length == 2) {
            n = pd + n.toString();
        }
        object.value = n;
    }
}


function ChksumCheckDigit(vin)
{
    vinChars = "ABCDEFGHJKLMNPRSTUVWXYZ1234567890";
    vinValues = new Array(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 7, 9, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
    vinWeights = new Array(8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2);
    sum = 0;

    for (i = 0; i < 17; ++i)
    {
        // extract the value of the VIN character
        if ((val = vinChars.indexOf(vin.charAt(i))) < 0)
            return ("error");

        // multiply the value of the VIN character
        // by the weight of its position in vinValues.
        // Add them up to get the sum
        sum += (vinValues[val] * vinWeights[i]);
    }

    // divide the sum by 11 to get the remainder
    remainder = sum % 11;

    // if the remainder is 10, the check digit is X
    if (remainder == 10)
        return 'X';

    // otherwise the remainder is the check digit (i.e., 0-9).
    return remainder.toString();
}

function RQBIError(msg)
{
    alert(msg);
}

// Gp.  ToolTip onmousover / onmouseout logic 
var lastTooltip = null;
var tooltipBackColor = '#f6f79a';
var browserWidth = 0, browserHeight = 0;
browserDims(); // get the browser dimensions

showTooltip = function(strTitle, strText, strHelpText, strhelpImage, strmainImage, jtfy, dRange)
{
    justfy = jtfy;
    var horLine = document.createElement("hr");
    horLine.style.width = '100%';
    horLine.style.clear = 'both';

    if (lastTooltip == null)
    {
        var newDiv = document.createElement("div");
        newDiv.style.background = tooltipBackColor;
        newDiv.style.color = '#000';
        newDiv.style.position = 'absolute';
        newDiv.style.width = '350px';
        newDiv.style.border = '#767676 1px solid';
        newDiv.style.padding = '0px 5px 0px 5px';
        newDiv.style.visibility = 'hidden';

        var title = document.createElement("span");
        title.style.padding = '6px 0px 4px 0px';
        newDiv.style.font = 'bold 11px "Verdana" , "Arial"';
        title.style.styleFloat = 'right';
        title.style.cssFloat = 'right';
        title.style.textAlign = 'right';
        title.style.clear = 'both';
        title.style.width = '100%';

        var repTitle = strTitle.replace("~~", "'");
        var titleItems = repTitle.split("|");
        for (var i = 0; i < titleItems.length; i++)
        {
            if (i > 0)
                title.appendChild(document.createElement("br"));
            var titleText = document.createTextNode(titleItems[i]);
            title.appendChild(titleText);
        }
        var mainParagraf = document.createElement("p");
        mainParagraf.style.font = 'normal 10px "Verdana" , "Arial"';
        mainParagraf.style.padding = '0 2px 6px 0px';
        mainParagraf.style.margin = '0';
        mainParagraf.style.styleFloat = 'right';
        mainParagraf.style.cssFloat = 'left';

        if (strmainImage)
        {
            var mainImg = document.createElement("img");
            mainImg.setAttribute("src", strmainImage);
            mainImg.width = "40";
            mainImg.height = "40";
            mainImg.style.font = 'bold 12px "Verdana" , "Arial"';
            mainImg.style.marginRight = '10px';
            mainImg.style.styleFloat = 'left';
            mainImg.style.cssFloat = 'left';
            mainParagraf.appendChild(mainImg);
        }
        if (justfy == 1)
        {
            var mainDateRange = document.createElement("span");
            mainDateRange.style.padding = '2px 0px 0px 0px';
            mainDateRange.style.styleFloat = 'left';
            mainDateRange.style.textAlign = 'center';
            mainDateRange.style.cssFloat = 'left';
            mainDateRange.style.clear = 'both';
            mainDateRange.style.width = '100%';
            mainDateRange.style.font = '200 10 "Verdana", "Arial"';
            var dateTitle = document.createTextNode(dRange);
            mainDateRange.appendChild(dateTitle);
        }
        var mainItems = strText.split("|");
        for (var i = 0; i < mainItems.length; i++)
        {
            if (i > 0)
                mainParagraf.appendChild(document.createElement("br"));
            var mainText = document.createTextNode(mainItems[i]);
            mainParagraf.appendChild(mainText);
        }
        if (justfy == 1) mainParagraf.appendChild(mainDateRange);
        newDiv.appendChild(title);
        newDiv.appendChild(horLine);
        newDiv.appendChild(mainParagraf);
        if (strHelpText)
        {
            var helpDiv = document.createElement("div");
            helpDiv.style.styleFloat = 'right';
            helpDiv.style.cssFloat = 'right';
            helpDiv.style.clear = 'both';
            helpDiv.style.paddingLeft = '6px';
            helpDiv.style.height = '24px';

            if (strhelpImage)
            {
                var helpImg = document.createElement("img");
                helpImg.setAttribute("src", strhelpImage);
                helpImg.style.marginRight = '8px';
                helpImg.style.verticalAlign = 'middle';
                helpDiv.appendChild(helpImg);
            }

            var helpText = document.createTextNode(strHelpText);
            helpDiv.appendChild(helpText);
            newDiv.appendChild(horLine);
            newDiv.appendChild(helpDiv);
        }

        lastTooltip = newDiv;
        if (document.addEventListener) document.addEventListener("mousemove", moveTooltip, true);
        if (document.attachEvent) document.attachEvent("onmousemove", moveTooltip);
        var bodyRef = document.getElementsByTagName("body").item(0);
        bodyRef.appendChild(newDiv);
    }
};

moveTooltip = function(e)
{
    if (lastTooltip)
    {
        if (document.all)
            e = event;
        if (e.target)
            sourceEl = e.target;
        else if (e.srcElement)
            sourceEl = e.srcElement;

        var coors = findPos(sourceEl);
        var positionLeft = e.clientX + 10;
        var positionTop = coors[1] + sourceEl.clientHeight + 20;
        if (positionTop > browserHeight - 210) positionTop -= 170;
        if (positionLeft > browserWidth - 120) positionLeft -= 170;
        if (justfy == 1) positionLeft -= 390;
        lastTooltip.style.top = positionTop + 'px';
        lastTooltip.style.left = positionLeft + 'px';
        lastTooltip.style.visibility = 'visible';
    }
}

hideTooltip = function()
{
    var bodyRef = document.getElementsByTagName("body").item(0);
    if (lastTooltip) bodyRef.removeChild(lastTooltip);
    lastTooltip = null;
};

function findPos(obj)
{
    var curleft = curtop = 0;
    if (obj.offsetParent)
    {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent)
        {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}

function setAjax(toggle)
{
    return true;
}

function beginReq(sender, args)
{
    // shows the modal at the beginning of the ajax beginRequest
    $find(ModalProgress).show();
}

function endReq(sender, args)
{
    if (args.get_error())
    {
        args.set_errorHandled(true);
    }
    // remove the begin / endrequest
    setAjax(0);
    //  hides after the ajax endRequest 
    $find(ModalProgress).hide();
}

function browserDims()
{
    // get height & width of current browser window
    if (typeof (window.innerWidth) == 'number')
    {
        //Non-IE
        browserWidth = window.innerWidth;
        browserHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        browserWidth = document.documentElement.clientWidth;
        browserHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        browserWidth = document.body.clientWidth;
        browserHeight = document.body.clientHeight;
    }
}

// Utlity to open the Schedule PopUp window
function openSchedule(bytype, submitID, scheduleType, key)
{
    if (bytype == 'byunit' && key != "")
    {
        var url = "Rate/ScheduleWrapper.aspx%3FsubmitID=" + submitID + "%26scheduleType=" + scheduleType + "%26unitKey=" + key;
        var win = window.open("../Loading.aspx?Page=" + url, "SRWorksheet", "width=700,status=no,titlebar=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes", true);
        win.opener = self;
    } else if (bytype == 'byscheduleid' && key != "")
    {
        var url = "Rate/ScheduleWrapper.aspx%3FsubmitID=" + submitID + "%26scheduleType=" + scheduleType + "%26scheduleID=" + key;
        var win = window.open("../Loading.aspx?Page=" + url, "SRWorksheet", "width=700,status=no,titlebar=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes", true);
        win.opener = self;
    }
    return false;
}

// validatorPostFix is the unmangled ID of the control - not the true client id
function SRWValidation(textbox, validatorPostFix, invalidToolText)
{
    if (typeof (Page_Validators) == 'undefined')
        return;

    if ($("*[id$='" + validatorPostFix + "']")[0].isvalid)
    {
        textbox.style.color = 'Black';
        textbox.style.backgroundColor = 'White';
        textbox.title = '';
    } else
    {
        textbox.style.color = 'White';
        textbox.style.backgroundColor = 'Red';
        textbox.title = invalidToolText;
    }
    return;
}

// Utlity to open the Print PopUp window
function openPrintDialog(transactionId, description, transactionType)
{
    if (transactionId != "")
    {
        var url = "PrintDialog.aspx%3FtransactionId=" + transactionId + "%26description=" + description + "%26transactionType=" + transactionType;
        var win = window.open("../Loading.aspx?Page=" + url, "PrintDialog", "width=600,height=500,status=no,titlebar=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes", true);
        win.opener = self;
    }
    return false;
}

// Utlity to open the Print PopUp window
function openPDFView(loadingurl, title)
{
    //var url = "PDFView.aspx%3Ftitle=" + title;
    var url = "Pdf/GetReport/" + title;
    window.open(loadingurl + "?Page=" + url, "", "width=800,height=600,scrollbars=yes,resizable=yes", true);
    return false;
}
function openSamplePDFView(loadingurl, formid, formedition, title) {


    var url = "Pdf/GetSampleReport/" + "&formid=" + formid + "&formedition=" + formedition + "&title=" + title;
    window.open(loadingurl + "?Page=" + url, "", "width=800,height=600,scrollbars=yes,resizable=yes", true);
    return false;
}

function tabOnEnterKey(event)
{
    if (navigator.userAgent.indexOf("MSIE")!=-1)
    {
         keyCode=(event.which)?event.which:event.keyCode;
         if(keyCode==13) 
         {
            event.keyCode=9;
         }
    }

    if (navigator.userAgent.indexOf("Firefox")!=-1)
    {
       var elem;
       var nextIndex = 999;
       
       if (event.keyCode == 13)
       {
           // if all input tab indices are 0
           if ($("input[tabIndex = 0]").length > 1)
           {
               // Apply indices to all input tab indices
               formFields = document.getElementsByTagName("input");
               for (i=0;i<formFields.length;i++)
               {
                    formFields[i].tabIndex = i;
               }
           }       
           
           elem = event.currentTarget;
                     
           currentIndex = elem.tabIndex;
 
           // probably really want to just get nodes for this form, not
           // entire doc.  Something like elem.parentNode.childNodes ?
           formFields = document.getElementsByTagName("input");
           for (i=0;i<formFields.length;i++)
           {
               if (formFields[i].nodeType == 1
                    && formFields[i].getAttribute("type") != "hidden"
                    && !formFields[i].readOnly)
               {
                   tabIndex = formFields[i].getAttribute("tabindex");
                   
                   if (tabIndex == null)
                   {
                       tabIndex = formFields[i].tabIndex;
                   }
                   
                   tabIndex = parseInt(tabIndex);
                   if((tabIndex < nextIndex) && (tabIndex > currentIndex))
                   {
                       nextIndex = tabIndex;
                       index = i;
                   }
               }
           }
           
           if (index == undefined)
           {
                index = elem.tabIndex;
           }
           
           //formFields[index].setAttribute('autocomplete', 'off');
           formFields[index].focus();
           event.preventDefault();
           event.stopPropagation();
           return false;
       }
    }
 }
 
// tab on enter key press
//function tabOnEnterKey(e)
//{
//    var key;
//    var event;
//    //debugger;
//    if (window.event) // IE
//    {
//        event = window.event;
//        key = event.keyCode;
//        if (key == 13)
//        {         
//            event.keyCode = 9;
//        }
//        return true;        
//    }
//     else if (e.which) // firefox
//    {
//        event = e;
//        key = event.keyCode;
//        if (key == 13)
//        {        
//            event.cancelBubble = true;
//            event.preventDefault();
//            event.returnValue = false;        
//            //event.keyCode = 9;
//        }
//        return true;        
//    }
//}

// Utility used by Rateset Common Effective Date 
function AddYear(date, defaultDate)
{
    if (Date.parseLocale(date) != null)
    {
        var d, y;
        d = new Date(date);
        y = d.getFullYear() + 1;
        d.setFullYear(y);
        return d.format("MM/dd/yyyy");
    }
    return defaultDate;
}

// Utility used by by Rateset Common Effective Date to correct 2 digit year entries
function CorrectTwoDigitDate(textbox, validator, centuryPrefix)
{
    var twoDigitDateRegEx = /^(0?[1-9]|1[012])[\/](0?[1-9]|[12][0-9]|3[01])[\/](\d\d)(__)?$/;
    if (twoDigitDateRegEx.exec(textbox.value))
    {
        textbox.value = textbox.value.replace(twoDigitDateRegEx, '$1/$2/' + centuryPrefix + '$3');
        var valid = validator.attributes.getNamedItem("isValid") != null ? validator.attributes.getNamedItem("isValid").value : validator.IsValid;
        if (valid == false)
            ValidatorValidate(validator);
    }
    return true;
}

function CreateServiceNowTicket(errorMessage, userInput, button)
{
    var params = '{ "errorMessage":"' + escape(errorMessage) + '", "userInput":"' + escape(userInput) + '" }';
    $(button).attr('disabled', 'disabled');
    $.ajax({
        type: "POST",
        url: '../Webservices/ServiceNow.asmx/CreateTicket',
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg)
        {
            if (eval(msg).d.indexOf('INC') > -1)
            {
                alert("Your incident number is " + eval(msg).d + " please keep track of this for future reference.");
            }
            else
            {
                alert(eval(msg).d);
            }
        }
    });
}

// Form Issuance tab on CAWorksheet, FormsIssuance.asxc, toggle divs
function ToggleAdditionalForms()
{
    var src = ($("#imageAdditionalForms").attr("src") === "../images/collapse.jpg") ? "../images/expand.jpg" : "../images/collapse.jpg";
    $("#imageAdditionalForms").attr("src", src);
    $('#divNewDocumentsMissing').slideToggle(300);
}

function CreateServiceNowTicket(errorMessage, userInput, button)
{
    var params = '{ "errorMessage":"' + escape(errorMessage) + '", "userInput":"' + escape(userInput) + '" }';
    $(button).attr('disabled', 'disabled');
    $.ajax({
        type: "POST",
        url: '../Webservices/ServiceNow.asmx/CreateTicket',
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg)
        {
            if (eval(msg).d.indexOf('INC') > -1)
            {
                alert("Your incident number is " + eval(msg).d + " please keep track of this for future reference.");
            }
            else
            {
                alert(eval(msg).d);
            }
        }
    });
}

// Garage Proposal Tab - change implementation
//validation from other textarea to restrict five lines only.
//BEGIN CHANGE: Garage Proposal Tab, validation of limit lines in textArea control.
function limitTextarea(el, maxLines, maxChar) {
     var lines = el.value.split('\n'), i = lines.length, lines_removed, char_removed;
        if (maxLines && i > maxLines) {
            alert('You can not enter more than ' + maxLines + ' lines');
            lines = lines.slice(0, maxLines);
            lines_removed = 1;
        }
        if (maxChar) {
            i = lines.length;
            while (i-- > 0) if (lines[i].length > maxChar) {
                lines[i] = lines[i].slice(0, maxChar);
                char_removed = 1;
            }
            if (char_removed) alert('You can not enter more than ' + maxChar + ' characters per line');
        }
        if (char_removed || lines_removed) el.value = lines.join('\n');
    }
//END CHANGE: Garage Proposal Tab, validation of limit lines in textArea control.

// This code needs to remain at the bottom of the file to inform ajax that it has compeleted load.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();



