﻿// JScript File
var zip;
var territory;
var GeoState;
var GlobalAllianceData;
var GlobalValidationResult;
var GlobalAgentID = "";
var AWSzipCodeChanged = false;
var GlobalLicensedStates;
var IsAgentLicensed = true;
var GlobalAgentName="";
var GlobalZip="00000";
var invalidZipFlag = false;
var urlArray = [null,null];
var zipCodeLiterals;
var pageName;
var validZip;
var newZipOverlayFlag = false;
var displayAWSmsg = false;

/****************DART Tag javascript Iteration 4 *************************/
function ProcessZipEntry(txtValue)
{ 
    var charCount = txtValue.value.length;
    
    if (charCount == 5){ 
        invalidZipFlag = false;
        if (zip != txtValue.value){
          //hide the AWS message
            $get('AWSZipCodeChangedMessage').style.display = "none";
         if (newZipOverlayFlag)
         {
            $get('AWSZipChangedMsg').style.display = 'none';
         }

         //User entered a five number zip code and it is not identical to the previous entry.
         zip = txtValue.value;
         //if user comes from AWS, set flag that zipcode changed.
         if (GlobalAgentID != "")
         {
            AWSzipCodeChanged = true;         
         }
        /*START FOR USD #6911089,6976742,6964667 FIX*/
        
        //Set the value to 0 if the zip code is changed
        self.parent.changedZipCode = 0;
        
        /*END FOR USD #6911089,6976742,6964667 FIX*/ 
        
        //Call GeoService to get state code for this zip.
        CallGeoService(zip);
        }
    }
}

function buildZipCodeChangedMessage(link)
{
    //sets up the zipcode
    $get("AWSZipCode").innerHTML = zip;
    
    //sets up the Agent Name
    $get("AWSAgentName").innerHTML = GlobalAgentName;
    
    //sets up the state string
    var GlobalLicensedStateArray = new Array();
    
    GlobalLicensedStateArray = GlobalLicensedStates.split(/,/);

    var length = GlobalLicensedStateArray.length;

    if (length > 2) //more than two states
    {
        var formattedStatesArray = new Array();

        var dupeStateFlag = new Boolean();
        dupeStateFlag = false;
        
        //prime the loop
        newState = GlobalLicensedStateArray.pop();
        formattedStatesArray.push(newState);
        length = length-1;
        //loop through remaining states if they are not duplicate then add to the array
        for (x=length; x >= 1; x--)
        {
            newState = GlobalLicensedStateArray.pop();
            for (y=formattedStatesArray.length; y >= 0; y--)
            {
                if (newState == formattedStatesArray[y])
                {    
                    dupeStateFlag = true;
                    break;
                }
            }
            if (dupeStateFlag == false) 
                formattedStatesArray.push(newState);
                
            dupeStateFlag = false;

        }

        var lastState = formattedStatesArray.pop();

        var stateString = formattedStatesArray.join(", ");
    
        $get("AWSAgentStates").innerHTML = stateString + " and " + lastState;        
    }
    else if (length == 2)//two states
    {
        var firstState = GlobalLicensedStateArray.pop();
        var secondState = GlobalLicensedStateArray.pop();
        
        if (firstState == secondState)
            $get("AWSAgentStates").innerHTML = firstState;
        else
            $get("AWSAgentStates").innerHTML = firstState + " and " + secondState;
    }
    else //one state
    {
        $get("AWSAgentStates").innerHTML = GlobalLicensedStateArray.pop();
    }
   
    //sets up the link
    $get("agentLocatorLink").href = link + "?ZipCode=" + zip;
}

function buildALRlink(link)
{ 
    //sets up the link
    $get("AlocatorLink").href = link + "?ZipCode=" + zip;

}

function CallGeoService(strZipCode)
{
    zip = strZipCode;
    //PageMethods.GetGeoZip(zip, ProcessGeoServiceResponse, processGeoAllianceError);
    if(newZipOverlayFlag == false)
    {
        PageMethods.GetGeoZip(zip, ProcessGeoServiceResponse, processError);
    }
    else
    {
        PageMethods.GetGeoZip(zip, ProcessGeoServiceResponseNewOverlay, processError);
    }

}

function ParseAgentQuery(query)
{
    //parse through query and set results into array delimited by '&'
    //This function is found in UIHelper.js
    //ParseAWSQueryString(query);
    //Once querystring is parsed and set to an object of key/value pair array,
    //look through parsed array to find licensed states and set results to Global variable
    GlobalLicensedStates = GetParamFromAgentQuerystring('LState');
    
    verifyAgentLicenseState();  
    
    GlobalAgentName = GetParamFromAgentQuerystring('AgentName');
    if (!newZipOverlayFlag)
    {
        PageMethods.GetAgentLocatorLink(buildZipCodeChangedMessage, processError);
    }
    else
    {
        PageMethods.GetAgentLocatorLink(buildZipCodeChangedMessageNewOverlay, processError);
    }
}


function CheckForAgentQuery()
{
     //get query string from session and return results to parseAgentQuery()
     //1st param is name of function that will get called upon sucess of PageMethod
     //the data returned from the PageMethod will get passed into the "success function" as a param.
    PageMethods.GetAgentQuery(ParseAgentQuery, processError);
   
}

function verifyAgentLicenseState()
{
    //if states are avail, verify that state of current zipcode is found in license state list.
    if(GlobalLicensedStates != 'false')
    {
        //parse through license states and compare with state returned from GEO service
        //3rd param is function name called on success of page method.
        PageMethods.IsAgentLicensed(GeoState, GlobalLicensedStates, SetIsAgentLicensed, processError);
            
        //display the message
       
    }
    else //compare to state of AWS page.
    {
        var awsState = GetParamFromAgentQuerystring('State');
        if (awsState != false)
        {
            if (awsState == GeoState)
            {
                SetIsAgentLicensed(true);
            }
            else
            {
                SetIsAgentLicensed(false);
            }
        }
    }
}

function SetIsAgentLicensed(flag)
{
    IsAgentLicensed = flag;
    if (newZipOverlayFlag)
    {
        //user entered zip code to an unlicensed state
        if (flag == false && invalidZipFlag == false)
        {
            //displayAWSmsg = false;
            $get('AWSZipChangedMsg').style.display = "none";
            self.parent.changedZipCode = zip;
        }
        //user entered a zip code to a licensed state.
        else
        {
            
            /*START FOR USD #6911089,6976742,6964667 FIX*/
            displayAWSmsg = false;
            $get('AWSZipChangedMsg').style.display = "none";
            //self.parent.changedZipCode = null;
            self.parent.changedZipCode = 0;
            
            /*END FOR USD #6911089,6976742,6964667 FIX*/ 

        }
    }
    else
    {
        //user entered zip code to an unlicensed state
        if (flag == false && invalidZipFlag == false)
        {
         $get('AWSZipCodeChangedMessage').style.display = "";
         self.parent.changedZipCode = zip;
        }
        //user entered a zip code to a licensed state.
        else
        {
            /*START FOR USD #6911089,6976742,6964667 FIX*/
            
            //self.parent.changedZipCode = null;
            self.parent.changedZipCode = 0;
            
            /*END FOR USD #6911089,6976742,6964667 FIX*/ 

        }
    }
}


//if we came from AWS and changed zip code to a state that the agent is not licensed in
//we need to ensure that the stream type stays out of AWS from this point on
//SetIsAgentLicensed(flag) changes the value of changedZipCode
//
//this function is added to select button as an eventlistener in addTerrSelectOnClickEvent()
//it resets the AWSzipCodeChanged to false and globalAgentID to empty string
//resetting the AWSzipCodeChanged prevents AWS functionality in ZipCodeModal.js 
//from happening on subsequent calls to the entry page
function setStreamType()
{
    if (self.parent.changedZipCode != null)
    {
        AWSzipCodeChanged = false;
        GlobalAgentID = "";
        //$get('Entry1800Message').style.display = "block";   
    }
}

function GetParamFromAgentQuerystring(key)
{
    //Function found in UIHelper.js
    var param = entryQueryString(key);
    if (param != null)
    {
       return param;
    }
    else
    {
        return null;
    }
}


function ProcessGeoServiceResponse(ValidationResult)
{
    GeoState = ValidationResult.sGeoState;
    GlobalValidationResult = ValidationResult.sStateInfo;
    validZip = ValidationResult.validZip;    
    
    //Check flag for whether zipcode coming from AWS was changed.
    //if user doesn't come from AWS, flag is set to 'false' by default
    if (AWSzipCodeChanged == true)
    {
        //If yes, verify new zipcode is a state in which agent is licensed
        CheckForAgentQuery();
    }
    
    if(ValidationResult.Territory != null)
    {
        resetZipMsg();
        ProcessValidState(ValidationResult.Territory);
    }
//    else if (GeoState == 'CA' || GlobalValidationResult != 'CallAlliance')
    else if(GlobalValidationResult != 'CallAlliance')
    {
        ProcessInactiveStates(GlobalValidationResult);
    }
    else if (GeoState == 'MA' || GeoState == '')
    {
        //Massachusetts or no state returned from GeoService for the zip code the user entered.
        //Display appropriate message based on what was returned. 
        ProcessNULLMassachusetts(GeoState);   
    }    
    else if (validZip == false)
    {
        DisplayInvalidZipCodeMessage(GeoState);
    }
}
function DisplayInvalidZipCodeMessage(GeoState)
    {
        modalBackImage = "url(images/1_2-entryPage-zipcodeNot_SideBorder.gif)";
        $get('ZipCodeModalWrapper').style.backgroundImage = modalBackImage;
        $get('pnlZipCode').style.backgroundImage = modalBackImage;
        $get('ZipCodeModalMultipleTerritories').style.display = 'none';
        $get('ZipCodeModalValidTerritory').style.display = 'none';
        $get('ZipCodeModalInvalidTerritory').style.display = 'block';
        $get('ZipCodeModalWhiteBody').style.marginBottom = '0px';
        $get('ZipCodeModalWrapper').style.backgroundColor = '#DDBB49';
        
        //hide Where do you live div, display We're sorry and inelgible zip message
        $get('IneligibleZIP').style.display = 'block';
        $get('WereSorry').style.display = 'block';
        $get('WhereDoYouLive').style.display = 'none';
        
        var divItem = $get('SelectAreaWrapper');
        divItem.style.display = 'block';
        divItem.style.paddingBottom = '0px';
       
        PageMethods.GetAgentLocatorLink(buildALRlink, processError);


    }


function ProcessNULLMassachusetts(stateCode){
    modalBackImage = "url(images/1_2-entryPage-zipcodeNot_SideBorder.gif)";
    $get('ZipCodeModalWrapper').style.backgroundImage = modalBackImage;
    $get('pnlZipCode').style.backgroundImage = modalBackImage;
    $get('ZipCodeModalMultipleTerritories').style.display = 'none';
    $get('ZipCodeModalValidTerritory').style.display = 'none';
    $get('ZipCodeModalInvalidTerritory').style.display = 'block';
    $get('ZipCodeModalWhiteBody').style.marginBottom = '0px';
    $get('ZipCodeModalWrapper').style.backgroundColor = '#DDBB49';
    $get('CancelMessageArea').style.color = '#A95343';
    var divItem = $get('SelectAreaWrapper');
    divItem.style.display = 'block';
    divItem.style.paddingBottom = '0px';
       
    if (stateCode == 'MA')
    {
        $get('CancelMessageArea').className = 'ZipCodeInvalid';
        var CancelMessageObj = $get('lblCancelMessage');
        var CancelMessageText = zipCodeLiterals.sorryNotOffered;        
        setInnerText(CancelMessageObj, CancelMessageText); 
    }
    //This gets triggered when Alliance cannot return territories for the zipcode entered.  ie: PO boxes.
    else if (stateCode == 'NA')
    {
        $get('CancelMessageArea').className = 'ZipCodeNotFound';
        var CancelMessageObj = $get('lblCancelMessage');
        var CancelMessageText = zipCodeLiterals.sorryZipNotFound;        
        setInnerText(CancelMessageObj, CancelMessageText); 
    }

    //This gets triggered when the Geoservice cannot find the zipcode that was entered by the user.  ie: zipcode = 00000
    else
    {   
        $get('CancelMessageArea').className = 'ZipCodeInvalid';
        var CancelMessageObj = $get('lblCancelMessage');
        var CancelMessageText = zipCodeLiterals.invalidZip;        
        setInnerText(CancelMessageObj, CancelMessageText);
        invalidZipFlag = true;
    }       
}

function ProcessValidState(AllianceData){
    //Set AllianceData JSON object
    setGlobalAllianceData(AllianceData);
    
    //If Geo returned a state but Alliance did not return any territories for that zip 
    //and state combo then that means we do not offer insurance in that zip, i.e. 12345.
    //12345 is a NY zip but no territories returned.
    if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories == null || GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length<1)
    {
        ProcessNULLMassachusetts('NA');
        return;   
    }
    
    //We want to make sure all the sibling nodes that may have been created via node
    //cloning are removed before we display the results of the users next zip search.
    //Doing this assures that the screen will display accordingly and empty divs will 
    //not be hanging on the screen.
    var node = $get('ValidStateTemplate');
    removeSiblingNodes(node);
    
    var divItem = $get('SelectAreaWrapper');
    divItem.style.display = 'block';
    //Hide invalid territory div
    $get('ZipCodeModalInvalidTerritory').style.display = 'none';
    //Show valid territory div
    $get('ZipCodeModalValidTerritory').style.display = 'block';
    $get('ZipCodeModalWhiteBody').style.marginBottom = '0px';

    //If more than one territory is returned from Alliance we want to
    //do multiple things.  Display a div that gives instructions to select one
    //of the multiple territories displayed on the screen, fix padding for display
    //purposes and set height and overflow properties of the area where the 'Select'
    //buttons appear.  We want multiple territories to appear in a scrollable area
    //to preserve the layout of the modal popup.
    if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length>1)
    {
        $get('ZipCodeModalMultipleTerritories').style.display = 'block';
        $get('ZipCodeModalSelect').style.marginBottom = '0px';
        $get('ZipCodeModalValidTerritory').style.height = '84px';//Sets height of scrollable area
        $get('ZipCodeModalValidTerritory').style.overflow = 'auto';//Creates scrollable area
    }
    else
    {
        $get('ZipCodeModalMultipleTerritories').style.display = 'none';
        $get('ZipCodeModalValidTerritory').style.height = '';
    }

    //Loop through all the territories returned and build div's that display
    //the city and state in addition to ta 'Select' button for each.    
    //for (var i=0; i<GlobalAllianceData.Territories.length; i++)
    
    if(GlobalAllianceData.StateCode != "CA")
    {
        for (var i=0; i<GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length; i++)
        {       
            
            //We know there is a territory but if the territory node has children nodes that are null
            //or blank the data is deemed incomplete and potentially incorrect, show special message.
            if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityName == null || GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityName == '')
             {
                ProcessNULLMassachusetts('NA');
                return;   
             }
                  
            var city;
            //Trim spaces off of city name
            city = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityName.replace(/^\s*|\s*$/g,"");
                    
            //Clone div
            cloneDIV('ZipCodeModalSelect', 'CloneContainer', i); 
            
            //Add click event to each select button that is displayed for each of the
            //territories.
            addTerrSelectOnClickEvent(i);       
         
            var StateMessageObj = $get('lblStateMessage' + '~' + i);
            //Need to append inside/outside city limits and county name if more than one
            //territory returned
            if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length>1 && GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName != null)
            {
                var StateMessageText = city + ', ' 
                   + GlobalAllianceData.StateCode + ' (' + GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityLimitInd + ' City Limits) '
                        + GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName + ' COUNTY';
            }
            else if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length>1 && GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName == null)
            {
                var StateMessageText = city + ', ' 
                    + GlobalAllianceData.StateCode + ' (' + GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityLimitInd + ' City Limits)';                        
            }
            else
            {
                var StateMessageText = city + ', ' + GlobalAllianceData.StateCode;        
            }
            setInnerText(StateMessageObj, StateMessageText);                 
       } //end for
   }
   else //CA specific logic
   {
       for (var i=0; i<GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length; i++)
            {       
                
                  
                var county;
                //Trim spaces off of city name
                county = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName.replace(/^\s*|\s*$/g,"");
                                
                //Clone div
                cloneDIV('ZipCodeModalSelect', 'CloneContainer', i); 
                
                //Add click event to each select button that is displayed for each of the
                //territories.
                addTerrSelectOnClickEvent(i);       
             
                var StateMessageObj = $get('lblStateMessage' + '~' + i);
                //For CA Alliance only returns County Names, not City Names
                var StateMessageText = county + " COUNTY, " + GlobalAllianceData.StateCode;
                setInnerText(StateMessageObj, StateMessageText);                 
           } //end for      
       
   }
   
    modalBackImage = "url(images/1_2-entryPag-zipcod-2return-sideBorder.gif)";
    $get('ZipCodeModalWrapper').style.backgroundImage = modalBackImage;
    $get('ZipCodeModalWrapper').style.backgroundColor = '#66B329';
    $get('pnlZipCode').style.backgroundImage = modalBackImage;
        
}

function ProcessInactiveStates(stateName){

    i=0;
    
    //Set AllianceData JSON object
    //setGlobalAllianceData(AllianceData);    
    
    var divItem = $get('SelectAreaWrapper');
    divItem.style.display = 'block';
    
    //We want to make sure all the sibling nodes that may have been created via node
    //cloning are removed before we display the results of the users next zip search.
    //Doing this assures that the screen will display accordingly and empty divs will 
    //not be hanging on the screen.
    var node = $get('ValidStateTemplate');
    removeSiblingNodes(node);
     
    //Hide invalid territory div
    $get('ZipCodeModalInvalidTerritory').style.display = 'none';
    $get('ZipCodeModalMultipleTerritories').style.display = 'none';
    $get('ZipCodeModalWhiteBody').style.marginBottom = '0px'; 
    $get('ZipCodeModalValidTerritory').style.height = '';
    //Show valid territory div
    $get('ZipCodeModalValidTerritory').style.display = 'block';
    
    
    
    //Clone div
    cloneDIV('ZipCodeModalSelect', 'CloneContainer', i);
    
    //Add click event to the select button
    addTerrSelectOnClickEvent(i);
    
    var StateMessageObj = $get('lblStateMessage' + '~' + i);
    var StateMessageText = stateName;
    
    setInnerText(StateMessageObj, StateMessageText);                 
      
    modalBackImage = "url(images/1_2-entryPag-zipcod-2return-sideBorder.gif)";
    $get('ZipCodeModalWrapper').style.backgroundImage = modalBackImage;
    $get('ZipCodeModalWrapper').style.backgroundColor = '#66B329'; 
    $get('pnlZipCode').style.backgroundImage = modalBackImage;
}

function removeSiblingNodes(node)
{
    while (node != null)
    {
        var sibling = node.nextSibling;
        
        if(sibling == undefined &&
            sibling == null)
        {
            return;
        }   
        
        if(navigator.userAgent.indexOf("MSIE")!=-1){
            sibling.outerHTML="  "; // modified code to fix IE6/IE7 bug: http://support.microsoft.com/default.aspx?scid=kb;EN-US;925014
        }
        else
        {
            sibling.parentNode.removeChild(sibling);
        }
    }
}

function CancelZipModal(){
    //determine if quote is motorcycle quote and pass relevant params to hitbox
    var quoteType = entryQueryString('quote');
    if (quoteType != "mc")
    { 
        Innovations_hbPageView('cancel_zip.aspx','/auto/overlay');//Call HitBox function to submit action
    }
    else
    {
        Innovations_hbPageView('cancel_zip.aspx','/motorcycle/overlay');//Call HitBox function to submit action
    }
   
    //Start of fix for IM44077
    modalBackImage = "url(images/1_2-entryPag-zipcod-2return-sideBorder.gif)";
    $get('ZipCodeModalWrapper').style.backgroundImage = modalBackImage;
    $get('ZipCodeModalWrapper').style.backgroundColor = '#66B329';
    $get('ZipCodeModalInvalidTerritory').style.display = 'none';
    $get('ZipCodeModalWhiteBody').style.marginBottom = '0px';
    $get('pnlZipCode').style.backgroundImage = modalBackImage;
    var txtBoxZipCode = $get('txtBoxZipCode');
    txtBoxZipCode.value = "";
    txtBoxZipCode.focus();
    resetZipMsg();
}

function resetZipMsg(){
        $get('IneligibleZIP').style.display = 'none';
        $get('WereSorry').style.display = 'none';
        $get('WhereDoYouLive').style.display = '';
}

function processError(error, response){
    top.window.location=urlHomeErrorPage;  //variable defined in Entry Page.  This takes the web.config appSettings urlAllstate
}

function processGeoAllianceError(error, response)
{
    if(error !== null) { alert(error.get_message()); }
}

function cloneDIV(templateDIV, parentDIV, index){
    var template = $get(templateDIV);
    var newNode = template.cloneNode(true);
    reIndexExistingNode(newNode, index);
    var divZipModal = $get(parentDIV);
    divZipModal.appendChild(newNode);
 }

function cancelSubmit(){
    return false;
}

function cancelEnterKey(){
    var panelDiv =  $get('pnlZipCode');
    var selectDiv = $get('SelectAreaWrapper');

    if (panelDiv.style.display != 'none' && selectDiv.style.display == 'none')
    {
        return false;
    }
    else
    {        
        return true;
    }
}

function setTerritoryValues(evt){

    var btnIndex = getEventElement(evt);
    index = btnIndex.value;
    
    if(GlobalValidationResult == 'CallAlliance')
    {    
        PageMethods.SetSessionItems(index, GlobalAllianceData,IsAgentLicensed, GlobalAgentID, processAlternateEntry, processError);
        //8E042: Adding HBX Tag c15 to include selected territory code
        territory = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[index].TerritoryCode;
    } 
     else
    {
        PageMethods.SetStateZipSession(zip, GeoState, processAlternateEntry, processError);
    }
    
    //determine if quote is motorcycle quote and pass relevant params to hitbox
    var quoteType = entryQueryString('quote');
    if (quoteType != "mc")
    { 
        Innovations_hbPageView('select_zip.aspx','/auto/overlay');//Call HitBox function to submit action   
    }
    else
    {
        Innovations_hbPageView('select_zip.aspx','/motorcycle/overlay');//Call HitBox function to submit action   
    }
       
    RequestDART('quoti792');
}
    
    //4E025
function processAlternateEntry()
{    
    //qQuote is either 'PQ' or null comes from querystring via Entrypage variable
    PageMethods.GetPersonalQuoteState( zip, GeoState, qQuote, handleURL, sinkNonErrors );
}

//setTerritoryValues
/*Fix to capture javascript/async error that Firefox3 produces.  
The error returned is 0 which is not a valid http status code
200 is valid okay code.*/
function sinkNonErrors( error, response )
{
    var statusCode = error.get_statusCode();

    if ( !( statusCode == 0 || statusCode == 200 ) || error.get_timedOut() )
    {
        processError( error, response );
    }
    //Firefox3 successful TODO: handle a success of GetPersonalQuoteState calling pagemethod to retrieve urlArray for handleURL
}

//successful PageMethod event for setTerritoryValues
function handleURL(inUrlArray)
{
    urlArray = inUrlArray;
    // (DEST = ‘WQB or DCI2)
    if (urlArray[0] == "WQB" || urlArray[0] == "DCI2")
        top.window.location.href = urlArray[1];
    else if (urlArray[0] == "MCQ")
        top.window.location.href = urlArray[1];
    //Else (DEST =’AET’)
    else if (urlArray[0] == "AET")
    {
        //window.location.href = urlArray[1];  this is causing js popup errors. to test this locally use your machine name
        //http://machine-name/ConfiguratorFrame.aspx?Quote=PQ .... seems to be doing a pageload before leaving, and then when config loads
        //appears to not be able to find top (iframe)
        top.URLDestination = "AET";
        submitPage();
    }
    else
        submitPage();
        
}


function submitPage(){
    
    document.forms[0].submit();
    
}

function setGlobalAllianceData(AllianceData){
    GlobalAllianceData = AllianceData;
}

function addTerrSelectOnClickEvent(index){
    var submitBtn = $get('imgBtnSelect' + '~' + index);
    submitBtn.value = index;
    if(window.addEventListener){ // Mozilla, Netscape, Firefox
        submitBtn.addEventListener('click', setTerritoryValues, false);
        submitBtn.addEventListener('click', setStreamType, false);
    } 
    else { // IE
        submitBtn.attachEvent('onclick', setTerritoryValues);
        submitBtn.attachEvent('onclick', setStreamType);
    } 
}   


if (Sys && Sys.Application) { Sys.Application.notifyScriptLoaded(); }

// Below function is called by switchLangModalExtender on EntryPageHeader.ascx to capture HBX measurements for Toggle link.

     function callHBXOnCancel(callingPage)
     {
         pageName = callingPage;  
         PageMethods.GetLanguage(onCancelSucceeded,null);    
           
     }
     
     // This function is called by setNewLang()method on ConfiguratorPage.master
     function callHBXOnContinue(callingPage)
     {
         pageName = callingPage;    
         PageMethods.GetLanguage(onContinueSucceeded,null);    
         
     }
      
     function onCancelSucceeded(result)
     {  
        var x = pageName;
        if(result == "ESPANOL")
        {
           item1 = "cancel_toggle_to_english";
           item2 = "/"+ pageName;
        }
        else
        {
           item1 = "cancel_toggle_to_spanish";
           item2 = "/" + pageName;
        }  
                   
        Innovations_hbPageView(item1,item2);   
     } 
        

     function onContinueSucceeded(result)
     {
        if(result == "ESPANOL")
        {
           item1 = "continue_toggle_to_english";
           item2 = "/"+ pageName;
        }
        else
        {
           item1 = "continue_toggle_to_spanish";
           item2 = "/" + pageName;
        }      
               
        Innovations_hbPageView(item1,item2);            
    }
    
     //Below two functions are called by contPersonalQuoteExtender_Matrix and contPersonalQuoteExtender_Summary Ajax extenders
    function callHBXOnNQ2Cancel(callingPage)
     {
         pageName = callingPage;  
         PageMethods.GetLanguage(onNQ2CancelSucceeded,null);  
     }
     
    function onNQ2CancelSucceeded(result)
    {
        var item1, item2;
        item1 = "no_NQ2";
        if(language == "ESPANOL")
        {
          item2 = "/"+ pageName;
        }
        else
        {
          item2 = "/" + pageName;
        }      
               
        Innovations_hbPageView(item1,item2);
     }
     
    function callHBXOnNQ2Continue(callingPage)
     {
         PageMethods.GetLanguage(onNQ2ContinueSucceeded,null);    
         pageName = callingPage; 
     }
     
    function onNQ2ContinueSucceeded(result)
    {
        var item1, item2;
        item1 = "continue_NQ2";
        if(language == "ESPANOL")
        {
           item2 = "/"+ pageName;
        }
        else
        {
           item2 = "/" + pageName;
        }      
               
        Innovations_hbPageView(item1,item2);
     }

    function ProcessGeoServiceResponseNewOverlay(ValidationResult)
    {
        GeoState = ValidationResult.sGeoState;
        GlobalValidationResult = ValidationResult.sStateInfo;
        validZip = ValidationResult.validZip;    
        
        //Check flag for whether zipcode coming from AWS was changed.
        //if user doesn't come from AWS, flag is set to 'false' by default
        if (AWSzipCodeChanged == true)
        {
            //If yes, verify new zipcode is a state in which agent is licensed
            CheckForAgentQuery();
        }
        
        if(ValidationResult.Territory != null)
        {
            resetZipMsgNewOverlay();
            ProcessValidStateNewOverlay(ValidationResult.Territory);
        }
   
        else if(GlobalValidationResult != 'CallAlliance')
        {
            ProcessInactiveStatesNewOverlay(GlobalValidationResult);
        }
        else if (GeoState == 'MA' || GeoState == '')
        {
            //Massachusetts or no state returned from GeoService for the zip code the user entered.
            //Display appropriate message based on what was returned. 
            ProcessNULLMassachusettsNewOverlay(GeoState);   
        }    
        else if (validZip == false)
        {
            DisplayInvalidZipCodeMessageNewOverlay(GeoState);
        }
    }
    
    function ProcessValidStateNewOverlay(AllianceData){
    //Set AllianceData JSON object
    setGlobalAllianceData(AllianceData);
    displayAWSmsg = true;
    //If Geo returned a state but Alliance did not return any territories for that zip 
    //and state combo then that means we do not offer insurance in that zip, i.e. 12345.
    //12345 is a NY zip but no territories returned.
    if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories == null || GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length<1)
    {
        ProcessNULLMassachusettsNewOverlay('NA');
        return;   
    }
        
    for (var i=0; i<6; i++)
    {
        //clear any previous results
        var RadioID = 'Terr' + i.toString();
        var lblIDTop = 'lblTerrTop' + i.toString();
        var lblIDBottom = 'lblTerrBottom' + i.toString();
        $get(RadioID).style.display = 'none';
        $get(lblIDTop).style.display = 'none';
        $get(lblIDBottom).style.display = 'none';
    }//end for
    
    $get('InvalidZipMsgArea').style.display = 'none';
    $get('UserMessageArea').style.display = 'none';
    $get('ValidTerritories').style.display = 'none';
    $get('AWSZipChangedMsg').style.display = 'none';
    
    //Find out if the quote comes from AWS
    var QuoteFromAWS = GetParamFromAgentQuerystring('AWSFlag');
    
    if ((GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length>1)||(QuoteFromAWS == 'Y')||((AWSzipCodeChanged == true)))
    {
        //build the top level message
        var TerrFoundCount = 0;
        var TerrFoundText = '';
        var TerrMessageText = ''; 
        if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length > 6)
            {
                TerrFoundCount = 6;
            }
        else
            {
                TerrFoundCount = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length;
            }
        
        switch (TerrFoundCount)
        {
            case 1:
                TerrFoundText = 'one location';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ':';
                break;
            
            case 2:
                TerrFoundText = 'two locations';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
                break;
                
            case 3:
                TerrFoundText = 'three locations';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
                break;
                
            case 4:
                TerrFoundText = 'four locations';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
                break;
                
            case 5:
                TerrFoundText = 'five locations';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
                break;
                
            case 6:
                TerrFoundText = 'six locations';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
                break;
            
            default:
                TerrFoundText = 'the following locations';
                TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
                
        }
        //var TerrMessageText = 'We found ' + TerrFoundText + ' in ' + GlobalAllianceData.ZipCode + ', please select yours:';
        var TerrMessageObj = $get('lblLocationMsg');
        setInnerText(TerrMessageObj, TerrMessageText); 
        $get('imgTopBorder').src = '/images/SplitNonPrefilled.gif';
        $get('AWSZipChangedMsg').style.display = 'none';
        $get('ValidTerritories').style.display = 'block';
        $get('lblLocationMsg').style.display = 'block';
        $get('lblFooter').style.top = '660px';
        $get('ImgLock').style.top = '653px';
        $get('ImgTrust').style.top = '651px';
    }
    else
    {
        //The new requirement is for non-split zips to go directly to the destination application.
        //So we will call the following functions that would normally be called if the user
        //clicks the only territory select button that would have been shown. That button would have
        //an index of zero.
        //We know there is a territory but if the territory node has children nodes that are null
        //or blank the data is deemed incomplete and potentially incorrect, show special message.
        if(GlobalAllianceData.StateCode != "CA")
        {
            if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[0].CityName == null || GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[0].CityName == '')
             {
                ProcessNULLMassachusettsNewOverlay('NA');
                return;   
             } 
         }
        $get('AWSZipChangedMsg').style.display = 'none'; 
        $get('imgTopBorder').src = '/images/MessagePanel.gif';
        var LoadingMessageObj = $get('lblMessage');
        var LoadingMessageText = 'Please wait. Loading...';      
        setInnerText(LoadingMessageObj, LoadingMessageText);
        $get('lblMessage').style.color = '#56A345';
        $get('lblMessage').style.left = '210px';
        $get('lblMessage').style.width = '200px'; 
        $get('UserMessageArea').style.display = 'block';
        $get('lblFooter').style.top = '420px';
        $get('ImgLock').style.top = '413px';
        $get('ImgTrust').style.top = '411px';
        //setTerritoryValuesNewOverlaySingleTerritory(0);
        //setStreamType();
        setTimeout( 'goToTarget(0);', 1000); // pause for 1 second
        return;
    }

    if(GlobalAllianceData.StateCode != "CA")
    {
        //new requirement to show only 6 territories.
        var maxTerrNumber = 0; 
        if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length > 6)
            {
                maxTerrNumber = 6;
            }
        else
            {
                maxTerrNumber = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length;
            }
        
        
        for (var i=0; i<maxTerrNumber; i++)
        {       
            
            //We know there is a territory but if the territory node has children nodes that are null
            //or blank the data is deemed incomplete and potentially incorrect, show special message.
            if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityName == null || GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityName == '')
             {
                ProcessNULLMassachusettsNewOverlay('NA');
                return;   
             }
                  
            var city;
            //Trim spaces off of city name
            city = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityName.replace(/^\s*|\s*$/g,"");
                    
            //Need to append inside/outside city limits and county name if more than one
            //territory returned
            if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length>1 && GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName != null)
            {
                var StateMessageTextTop = city + ', ' + GlobalAllianceData.StateCode;
                var StateMessageTextBottom = '(' + GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityLimitInd + ' City Limits) '
                        + GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName + ' COUNTY';
            }
            else if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length>1 && GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName == null)
            {
                var StateMessageTextTop = city + ', ' + GlobalAllianceData.StateCode;
                var StateMessageTextBottom = '(' + GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CityLimitInd + ' City Limits)';                        
            }
            else
            {
                var StateMessageTextTop = city + ', ' + GlobalAllianceData.StateCode;
                var StateMessageTextBottom ='';        
            }
            var RadioID = 'Terr' + i.toString();
            var lblIDTop = 'lblTerrTop' + i.toString();
            var lblIDBottom = 'lblTerrBottom' + i.toString();
            $get(RadioID).style.display = 'block';
            $get(lblIDTop).style.display = 'block';
            $get(lblIDBottom).style.display = 'block';
            var RadioMessageObjTop = $get(lblIDTop);
            setInnerText(RadioMessageObjTop, StateMessageTextTop);
            var RadioMessageObjBottom = $get(lblIDBottom);
            setInnerText(RadioMessageObjBottom, StateMessageTextBottom);              
                             
       } //end for
   }
   else //CA specific logic
   {
       //new requirement to show only 6 territories.
        var maxTerrNumber = 0; 
        if (GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length > 6)
            {
                maxTerrNumber = 6;
            }
        else
            {
                maxTerrNumber = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory.length;
            }
       
       for (var i=0; i<maxTerrNumber; i++)
            {       
                var county;
                //Trim spaces off of county name
                county = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[i].CountyName.replace(/^\s*|\s*$/g,"");
               
                //For CA Alliance only returns County Names, not City Names
                var StateMessageTextTop = county + " COUNTY, " + GlobalAllianceData.StateCode;
                var StateMessageTextBottom ='';
                //setInnerText(StateMessageObj, StateMessageText);
                var RadioID = 'Terr' + i.toString();
                var lblIDTop = 'lblTerrTop' + i.toString();
                var lblIDBottom = 'lblTerrBottom' + i.toString();
                $get(RadioID).style.display = 'block';
                $get(lblIDTop).style.display = 'block';
                $get(lblIDBottom).style.display = 'block';
                var RadioMessageObjTop = $get(lblIDTop);
                setInnerText(RadioMessageObjTop, StateMessageTextTop);
                var RadioMessageObjBottom = $get(lblIDBottom);
                setInnerText(RadioMessageObjBottom, StateMessageTextBottom);                 
           } //end for      
       
   }          
}
function resetZipMsgNewOverlay(){
        displayAWSmsg = false;
        var RadioID = 'Terr0';
        $get(RadioID).checked=true;
        $get('UserMessageArea').style.display = 'none';
        $get('InvalidZipMsgArea').style.display = 'none';
        $get('ValidTerritories').style.display = 'none';
        $get('AWSZipChangedMsg').style.display = 'none';
        $get('imgTopBorder').src = '/images/SmallBackPanel.gif';
        $get('lblFooter').style.top = '390px';
        $get('ImgLock').style.top = '383px';
        $get('ImgTrust').style.top = '381px';
}
    function setTerritoryValuesNewOverlaySingleTerritory(index){

    if(GlobalValidationResult == 'CallAlliance')
    {    
        PageMethods.SetSessionItems(index, GlobalAllianceData,IsAgentLicensed, GlobalAgentID, processAlternateEntry, processError);
        //8E042: Adding HBX Tag c15 to include selected territory code
        territory = GlobalAllianceData.selectResponse.selectTerrResponse.selectTerritories.selectTerritory[index].TerritoryCode;
    } 
     else
    {
        PageMethods.SetStateZipSession(zip, GeoState, processAlternateEntry, processError);
    }
    
    //determine if quote is motorcycle quote and pass relevant params to hitbox
    var quoteType = entryQueryString('quote');
    if (quoteType != "mc")
    { 
        Innovations_hbPageView('select_zip.aspx','/auto/overlay');//Call HitBox function to submit action   
    }
    else
    {
        Innovations_hbPageView('select_zip.aspx','/motorcycle/overlay');//Call HitBox function to submit action   
    }
       
    RequestDART('quoti792');
}

function ProcessNULLMassachusettsNewOverlay(stateCode){
    displayAWSmsg = false;
    $get('AWSZipChangedMsg').style.display = 'none';
    $get('InvalidZipMsgArea').style.display = 'none';
    $get('ValidTerritories').style.display = 'none';
       
    if (stateCode == 'MA')
    {
        $get('imgTopBorder').src = '/images/MessagePanel.gif';
        var NotOfferedMessageObj = $get('lblMessage');
        var NotOfferedMessageText = zipCodeLiterals.sorryZipNotOffered;        
        setInnerText(NotOfferedMessageObj, NotOfferedMessageText);
        $get('lblMessage').style.color = '#A9302A';
        $get('lblMessage').style.left = '110px';
        $get('lblMessage').style.width = '400px';
        $get('UserMessageArea').style.display = 'block';
        $get('lblFooter').style.top = '420px';
        $get('ImgLock').style.top = '413px';
        $get('ImgTrust').style.top = '411px';  
    }
    //This gets triggered when Alliance cannot return territories for the zipcode entered.  ie: PO boxes.
    else if (stateCode == 'NA')
    {
        $get('imgTopBorder').src = '/images/MessagePanel.gif';
        var NotFoundMessageObj = $get('lblMessage');
        var NotFoundMessageText = zipCodeLiterals.sorryZipNotFound;        
        setInnerText(NotFoundMessageObj, NotFoundMessageText);
        $get('lblMessage').style.color = '#A9302A';
        $get('lblMessage').style.left = '90px';
        $get('lblMessage').style.top = '350px';
        $get('lblMessage').style.width = '400px';
        $get('UserMessageArea').style.display = 'block';
        $get('lblFooter').style.top = '420px';
        $get('ImgLock').style.top = '413px';
        $get('ImgTrust').style.top = '411px'; 
    }

    //This gets triggered when the Geoservice cannot find the zipcode that was entered by the user.  ie: zipcode = 00000
    else
    {   
        $get('imgTopBorder').src = '/images/MessagePanel.gif';
        var InvalidZipMessageObj = $get('lblMessage');
        var InvalidZipMessageText = 'The ZIP code you entered isn\'t recognized. Please re-enter.';                
        setInnerText(InvalidZipMessageObj, InvalidZipMessageText);
        $get('lblMessage').style.color = '#A9302A';
        $get('lblMessage').style.left = '110px';
        $get('lblMessage').style.width = '400px';
        $get('UserMessageArea').style.display = 'block';
        $get('lblFooter').style.top = '420px';
        $get('ImgLock').style.top = '413px';
        $get('ImgTrust').style.top = '411px'; 
        invalidZipFlag = true;
    }       
}

function DisplayInvalidZipCodeMessageNewOverlay(GeoState)
    {
        displayAWSmsg = false;
        PageMethods.GetAgentLocatorLink(buildALRlinkNewOverlay, processError);
        $get('imgTopBorder').src = '/images/MessagePanel.gif';
        var InvalidZipMessageObj = $get('lblMessage');
        $get('UserMessageArea').style.display = 'none';
        $get('ValidTerritories').style.display = 'none';
        $get('InvalidZipMsgArea').style.display = 'block'
        $get('AWSZipChangedMsg').style.display = 'none';
        $get('lblFooter').style.top = '420px';
        $get('ImgLock').style.top = '413px';
        $get('ImgTrust').style.top = '411px'; 

    }

function buildALRlinkNewOverlay(link)
{ 
    //sets up the link
    $get("AgtNewOverlayLink").href = link + "?ZipCode=" + zip;

}

function UserTerritorySelection()
{
    var SelectedIndex = 0;
    //find the selected radio button
    for (i=0;i<6;i++)
    {
        var RadioID = 'Terr' + i.toString();
        var RadObj = $get(RadioID);
        if (RadObj.checked == true)
        {
            SelectedIndex = i;
            break; 
        }
    }//end for   
    $get('ValidTerritories').style.display = 'none';
    $get('AWSZipChangedMsg').style.display = 'none';
    $get('imgTopBorder').src = '/images/MessagePanel.gif';
    var LoadingMessageObj = $get('lblMessage');
    var LoadingMessageText = 'Please wait. Loading...';      
    setInnerText(LoadingMessageObj, LoadingMessageText);
    $get('lblMessage').style.color = '#56A345';
    $get('lblMessage').style.left = '210px';
    $get('lblMessage').style.width = '200px'; 
    $get('UserMessageArea').style.display = 'block';
    $get('lblFooter').style.top = '420px';
    $get('ImgLock').style.top = '413px';
    $get('ImgTrust').style.top = '411px';
    //setTerritoryValuesNewOverlaySingleTerritory(SelectedIndex);
    //setStreamType();
    setTimeout( 'goToTarget('+ SelectedIndex + ');', 1000); // pause for 1 second
}

function ProcessInactiveStatesNewOverlay(stateName){
    i=0;
    displayAWSmsg = false;  
    
    for (var j=0; j<6; j++)
    {
        //clear any previous results
        var RadioID = 'Terr' + j.toString();
        var lblIDTop = 'lblTerrTop' + j.toString();
        var lblIDBottom = 'lblTerrBottom' + j.toString();
        $get(RadioID).style.display = 'none';
        $get(lblIDTop).style.display = 'none';
        $get(lblIDBottom).style.display = 'none';
    }//end for
    
    $get('InvalidZipMsgArea').style.display = 'none';
    $get('UserMessageArea').style.display = 'none';
    $get('ValidTerritories').style.display = 'none';
    $get('AWSZipChangedMsg').style.display = 'none';
    $get('imgTopBorder').src = '/images/MessagePanel.gif';
    var LoadingMessageObj = $get('lblMessage');
    var LoadingMessageText = 'Please wait. Loading...';      
    setInnerText(LoadingMessageObj, LoadingMessageText);
    $get('lblMessage').style.color = '#56A345';
    $get('lblMessage').style.left = '210px';
    $get('lblMessage').style.width = '200px'; 
    $get('UserMessageArea').style.display = 'block';
    $get('lblFooter').style.top = '420px';
    $get('ImgLock').style.top = '413px';
    $get('ImgTrust').style.top = '411px';
    //setTerritoryValuesNewOverlaySingleTerritory(0);
    //setStreamType();
    setTimeout( 'goToTarget(0);', 1000);//pause for 1 second 
}

function buildZipCodeChangedMessageNewOverlay(link)
{
    if (!displayAWSmsg) return;
    
    var strMessageText = ''; 
        
    //sets up the state string
    var GlobalLicensedStateArray = new Array();
    
    GlobalLicensedStateArray = GlobalLicensedStates.split(/,/);

    var length = GlobalLicensedStateArray.length;

    if (length > 2) //more than two states
    {
        var formattedStatesArray = new Array();

        var dupeStateFlag = new Boolean();
        dupeStateFlag = false;
        
        //prime the loop
        newState = GlobalLicensedStateArray.pop();
        formattedStatesArray.push(newState);
        length = length-1;
        //loop through remaining states if they are not duplicate then add to the array
        for (x=length; x >= 1; x--)
        {
            newState = GlobalLicensedStateArray.pop();
            for (y=formattedStatesArray.length; y >= 0; y--)
            {
                if (newState == formattedStatesArray[y])
                {    
                    dupeStateFlag = true;
                    break;
                }
            }
            if (dupeStateFlag == false) 
                formattedStatesArray.push(newState);
                
            dupeStateFlag = false;

        }

        var lastState = formattedStatesArray.pop();

        var stateString = formattedStatesArray.join(", ");
        
        strMessageText = GlobalAgentName + " is only able to help with quotes in " + stateString + " and " + lastState;
        
    }
    else if (length == 2)//two states
    {
        var firstState = GlobalLicensedStateArray.pop();
        var secondState = GlobalLicensedStateArray.pop();
        
        if (firstState == secondState)
            strMessageText = GlobalAgentName + " is only able to help with quotes in " + firstState;
        else
            strMessageText = GlobalAgentName + " is only able to help with quotes in " + firstState + " and " + secondState;
    }
    else //one state
    {
        strMessageText = GlobalAgentName + " is only able to help with quotes in " + GlobalLicensedStateArray.pop();
    }
    strMessageText = strMessageText + ". Select below to proceed or ";
    //sets up the link
    var AWSLinkObj = $get('lblAWSlink');
    var AWSlinkText = strMessageText + 'click here to locate another agent for ZIP ' + zip + '.';
    setInnerText(AWSLinkObj, AWSlinkText);
    $get('lblLocationMsg').style.display = 'none';
    $get('AWSZipChangedMsg').style.display = 'block';
    var NewAWSref = id('AWSNewlink');
    if (!NewAWSref) return;
    NewAWSref.href =  link + "?ZipCode=" + zip
}

function FocusToTxtBox()
    {
        var zipTextBoxTarget = $get("txtzipCode");
        zipTextBoxTarget.focus();
    }

    function id(name) {
        return document.getElementById(name);
    }

    function getStyle(elem, name) {
        if (elem.style[name])
            return elem.style[name];
        else if (elem.currentStyle)
            return elem.currentStyle[name];
        else if (document.defaultView && document.defaultView.getComputedStyle) {
            name = name.replace(/([A-Z])/g, "-$1");
            name = name.toLowerCase();
            var s = document.defaultView.getComputedStyle(elem, "");
            return s && s.getPropertyValue(name);
        } else
            return null;
    }


    function getHeight(elem) {
        return parseInt( getStyle( elem, 'height' ) );
    }

    function getWidth( elem ) {
       return parseInt( getStyle( elem, 'width' ) );
    }

    function scrollX() {
        var de = document.documentElement;
        return self.pageXOffset ||
            (de && de.scrollLeft) ||
            document.body.scrollLeft;
    }

    function scrollY() {
        var de = document.documentElement;

        return self.pageYOffset ||
            (de && de.scrollTop) ||
            document.body.scrollTop;
    }

    function windowHeight() {
        var de = document.documentElement;

        return self.innerHeight ||
            (de && de.clientHeight) ||
            document.body.clientHeight;
    }

    function windowWidth() {
        var de = document.documentElement;

        return self.innerWidth ||
            (de && de.clientWidth) ||
            document.body.clientWidth;
    }

    function setX(elem, pos) {
        elem.style.left = pos + "px";
    }

    function setY(elem, pos) {
        elem.style.top = pos + "px";
    }

    function adjust() {
        var obj = id('NewZipCode');
        if (!obj) return;

        var w = getWidth(obj);
        var h = getHeight(obj);
        
        //if we don't want to centre vertically then just set t= position you want
        var t = 20;
        //var t= scrollY() + (windowHeight() / 2) - (h / 2);
        //if (t < 0) t = 0;
        var l = scrollX() + (windowWidth() / 2) - (w / 2);
        if (l < 0) l = 0;

        setY(obj, t);
        setX(obj, l);
        
    }

    function goToTarget(index){
        setTerritoryValuesNewOverlaySingleTerritory(index);
        setStreamType();
    }

    window.onresize = adjust;
    window.onload = adjust;  

