﻿var map;
var baseIcon1 = null;
var baseIconSrc = null;
var baseIconDst = null;
var baseIconNonClickable = null;
var srcMarkers = null;
var dstMarkers = null;
var isDstActive = 1;
var srcFullMarkers = null;

var townMarkers = null;

var selectedMarkers = new Array(2);

var selectedCount = 0;

var worldLat = 48.69096039092549;
var worldLng = -32.34375;
var worldZoom = 2;

var USALat = 37.8575;
var USALng = -100.546875;
var USAZoom = 4;
var townsBufSrc = null;
var townsBufDst = null;
var GoogleMap = 0;
var listMenu;
var arrow;
var first_changeCommodity = 1;
var color_blink = "#9dcb8f";
var timeColor;
var cntColor = 0;
var elIdColor;
var timerRunning = false;
var errClr = "#EA8664";
var firstChContType = true;
var home1flg = 0;
var carsFlg = 0;
var carsInContPath = "";
var pathModifier = "";
var HHGPath = "";
var alternateAnimElIdColor = '';
var altCount = 0;
var presel_c = 0;
var detHeader;
var detVal;
var nSurchEveryCont;
var NYCTownID = 0;
var NYCStates = null;
var PathHHG = "";
var PathCARS = "";
var PathFCL = "";
var PathRORO = "";
var PathLCL = "";
var presel_ref = 0;
var gdir;
var dirEnable = true;
var isEC_HP = false;
var _logCallFlg = "unique_string_195id23984576";

function logCall(   // logCallFlg,
    msg, args) {
    if (typeof console == "undefined" || !(typeof logCallFlg == "undefined" || logCallFlg == _logCallFlg) || typeof args == "undefined")
        return;
    for (var i = 0; i < args.length; i++)
        msg += "; " + args[i];
    console.log(msg);
}

function CheckSteps(showToStep1) {
    var showToStep = showToStep1;
    if (home1flg && showToStep == 3) {
        showToStep = 4;
    }
    if (selectedMarkers[0] != null && selectedMarkers[1] != null) {
        var i;
        for (i = 3; i <= showToStep; i++) {
            var el = document.getElementById("step" + i);
            if (el) {
                if (i == 3 || i == 4) {
                    el.style.visibility = "visible";
                }
                else {
                    el.style.display = "";
                }
            }
            
        }
        document.getElementById("cont_info").style.display = "";
        if (showToStep == 3 || showToStep == 5) {
            gotobot();
        }
        if (showToStep == 3 && document.getElementById("selectCont").selectedIndex > 0) {
            CheckSteps(4);
        }
        if (showToStep == 4 && GetSelectedId("cmtype")!="start") {
            CheckSteps(5);
            document.getElementById("step41").style.visibility = "visible";
        }
        if (!isEC_HP) { // todo:EC
            document.getElementById("hintimg0").style.visibility = "";
            document.getElementById("hintimg1").style.visibility = "";
        }
    }
    else {
        for (var i = 3; i <= 6; i++) {
            var el = document.getElementById("step" + i);
            if (el) {
                if (i == 3 || i == 4) {
                    el.style.visibility = "hidden";
                }
                else {
                    el.style.display = "none";
                }
            }
        }
        document.getElementById("cont_info").style.display = "none";
        document.getElementById("step41").style.visibility = "hidden";
        if (!isEC_HP) { // todo:EC
            document.getElementById("hintimg0").style.visibility = "hidden";
            document.getElementById("hintimg1").style.visibility = "hidden";
        }        
    }
}
function CheckShowPrice() {
    var el = document.getElementById("step6");
    if (!el)
        return;
    var flg = CalcPrice(0);
    logCall("CheckShowPrice: " + flg);
    el.style.display = flg ? "" : "none";
}
function CalcPrice(showAlert) {
    if (selectedMarkers[0] == null || selectedMarkers[1] == null) {
        if (showAlert)
            alert('Please select Destination and Origin cities');
        return 0;
    }
    var chk = GetSelectedId("selectCont");
    if (chk == "start") {
        if (showAlert) {
            alert('Please select Type of container');
        }
        return 0;
    }
    chk = GetSelectedId("cmtype");
    if (chk == "start") {
        if (showAlert) {
            alert('Please select Type of commodity');
        }
        return 0;
    }
    chk = document.getElementById("numCont").value;
    if (!chk || chk == "")
    {
        if (showAlert) {
            alert('Please input number of countainers');
        }
        return 0;
    }
    clearBkColorId("numCont");
    if (!isEC_HP)
        document.getElementById("step6").style.display = "";
    if (isEC_HP) {
        if (isBlank(jQuery(get_origzip_clientid())[0].value)) {
            showAnimColor(get_origzip_clientid().substring(1));
            if (showAlert)
                alert('To get complete price, please, input pick-up place ZIP');
        }        
        else {
            // document.getElementById("step6").style.display = ""; // too early, table will look ugly in UI
            calcEcPickUp();
        }
    }
    else GetDist();
    
    if (showAlert) {
        var el1 = document.getElementById('puzip');
        if (el1) {
            if (el1.value == null || el1.value == '') {
                showAnimColor('puzip');
            }
        }
    }
    
    return 1;
}
function SlidePrice(val) {
    var addId = "";
    if (val) {
        addId = "2";
    }
    var el = document.getElementById("bda1" + addId);
    var elPriceDet = document.getElementById("priceDet" + addId);
    if (el && elPriceDet) {
        if (elPriceDet.style.display != "none") {
            el.innerHTML = "(break down)";
        }
        else {
            el.innerHTML = "hide table<img src='images/reset1.gif' style='vertical-align:middle' />";

        }
    }
    $("#priceDet" + addId).slideToggle("slow");
}
function SlidePrice1() {
    var el = document.getElementById("bda1");
    var elPriceDet = document.getElementById("priceDet");
    if (el && elPriceDet) {
        if (elPriceDet.style.display != "none") {
            el.innerHTML = "(break down)";
            elPriceDet.style.display = "none";
        }
        else {
            el.innerHTML = "hide table";
            elPriceDet.style.display = "";
        }
    }
}
function ProgrLoad(val)
{
    if (isEC_HP)
        return;
    var el = document.getElementById("tdload");
    var el1 = document.getElementById("tdload1");
    if (val) {
        el.style.display = "";
        el1.style.display = "none";
    }
    else 
    {
        el.style.display = "none";
        el1.style.opacity = 0;
        el1.style.display = "";
        $('#tdload1').animate({
			opacity: 1
		}, 600 );
    }
}
function markerTownClick(value) {
    logCall("markerTownClick: " + selectedCount, arguments);
    if (selectedCount < 2) {
        if (selectedMarkers[0] == null) {
            selectedCount = 0;
        }
        else {
            selectedCount = 1;
        }
        SelectTown(townMarkers[value].id, selectedCount);
        SetCountrySelectMode(false, true);
        selectedCount++;
    }
    if (selectedCount > 1) {
        ShowMarkers(false, srcMarkers);
        ShowMarkers(false, dstMarkers);
        FireEcDdlGeoItemSelectedEvent(GetOriginCityClientId());
    }
}

function FireEcDdlGeoItemSelectedEvent(elId) {
    if (!isEC_HP)
        return;
    gFiringEcEvent = true;
    var el = document.getElementById(elId);
    // showAjaxLoading('tdload1', true); // replaced with UpdateProgress server control
    if (document.all)
        el.fireEvent('onchange');
    else {
        var e = document.createEvent('HTMLEvents');
        e.initEvent('change', false, false);
        el.dispatchEvent(e);
    }
    // showAjaxLoading('tdload1', false);
    gFiringEcEvent = false;
}

function markerCountryClick(value) {
    logCall("markerCountryClick: " + isDstActive, arguments);
    Clear2Anim();
    if (isDstActive)
        ShowTowns(dstMarkers[value].id, 1, dstMarkers[value].marker.getTitle()/*ECr country name - country has no ID in ECr */, true);
    else ShowTowns(srcMarkers[value].id, 0, srcMarkers[value].marker.getTitle(), true);
}

function aaa() {
    ShowTowns();
}

function GetDestCountryClientId() {
    return isEC_HP ? get_destcountry_clientid() : "selCountry0";
}
function GetOriginStateClientId() {
    return isEC_HP ? get_originstate_clientid() : "selCountry1";
}
function GetDestCityClientId() {
    return isEC_HP ? get_destcity_clientid() : "selTown0";
}
function GetOriginCityClientId() {
    return isEC_HP ? get_origincity_clientid() : "selTown1";
}

function ChangeDestCountry() {
    logCall("ChangeDestCountry: " + gFiringEcEvent, arguments);
    if (gFiringEcEvent)
        return;
    var countryId = GetSelectedId(GetDestCountryClientId()), ecCountryName = "";
    if (isEC_HP)
    {
        var parts = countryId.split('-');
        countryId = parts[parts.length - 1];
        ecCountryName = parts[1];
        logCall("ChangeDestCountry: data: ", [countryId, ecCountryName]);
    }
    RemoveSelectedMarker(0);
    RemoveSelectedMarker(1);
    selectedCount = 0;
    Clear2Anim();
    if (countryId > 0) {
        ShowTowns(countryId, 1, ecCountryName);
        var i = 1;
        // alert('here');
        if (!isEC_HP) { // todo:ECar ?
            document.getElementById("selLabel" + i).style.visibility = "hidden";
            document.getElementById("selimage" + i).style.visibility = "hidden";
            document.getElementById("selTown" + i).style.visibility = "hidden";
            document.getElementById("selCountry" + i).style.visibility = "hidden";
        }
        document.getElementById(getStepDomId("step10")).style.display = "none";
        document.getElementById(getStepDomId("step11")).style.display = "none";
        document.getElementById("cont_info").style.display = "none";
    }
    else {
        ClearMarkers();
        RemoveSelectedMarker(0);
        RemoveSelectedMarker(1);
        if (!isEC_HP) // unnec.
            document.getElementById(GetDestCityClientId()).selectedIndex = 0;
        SetCountrySelectMode(true);
    }
    CheckShowPrice();
}
function ChangeSrcCountry() {
    logCall("ChangeSrcCountry: " + gFiringEcEvent, arguments);
    if (gFiringEcEvent)
        return;
    var countryId = GetSelectedId(GetOriginStateClientId());
    if (isEC_HP)
        document.getElementById("cont_info").style.display = "none";
    RemoveSelectedMarker(1);
    selectedCount = 1;
    if (!isEC_HP && countryId > 0 || isEC_HP && countryId != "") {
        ShowTowns(countryId, 0);
    }
    else {
        ClearMarkers();
        RemoveSelectedMarker(1);
        document.getElementById(GetOriginCityClientId()).selectedIndex = 0;
        ShowTowns(0, 0);
//        SetCountrySelectMode(false);
    }
    CheckShowPrice();
}
function ChangeContainer(val) {
    var countType = GetSelectedId("selectCont");
    if (countType != "start") {
        CheckSteps(4);
        var commType = GetSelectedId("cmtype");
        if (commType == "start") {
            showAnimColor("cmtype");
        }
    }
    var chk = document.getElementById("numCont").value;
    CheckShowPrice();
    if (!chk || chk == "" || firstChContType)
    {
        // showAnimColor("numCont");
    }
    if (firstChContType) {
        document.getElementById("step6").style.display = "none";
    }
    first_changeCommodity = 0;
    firstChContType = false;
}
function ChangeCommodity() {
    var countType = GetSelectedId("cmtype");
    if (countType == "LCL") {
        document.location = "http://www.oceanfreightusa.com";
        return;
    }
    if (countType != "start" && countType.substr(0, 3) == "Com") {
        CheckSteps(4);
    }
    if (countType != "start" && countType.substr(0, 3) != "Com") {
        document.location = "ShippingCarsHouseholdGoodsUsaBySea.aspx";
        return;
    }
    var contType = GetSelectedId("selectCont");
    if (contType == "start") {
        showAnimColor("selectCont");
    }
    
    CheckShowPrice();
    if (!home1flg) {
        first_changeCommodity = 0;
    }
}
function ChangeCommodity1() {
    var countType = GetSelectedId("cmtype");
    if (countType == "FCL") {
        showAnimColor("selectCont");
        CheckShowPrice();
        return;
    }
    if (countType == "HHG") {
        document.location = PathHHG;
        return;
    }
    if (countType == "LCL") {
        document.location = PathLCL;
        return;
    }
    if (countType == "CARS") {
        document.location = PathCARS;
        return;
    }
    if (countType == "RORO") {
        document.location = PathRORO;
        return;
    }   
}

function ChangeDestTown() {
    logCall("ChangeDestTown: " + gFiringEcEvent, arguments);
    if (gFiringEcEvent)
        return;
    selectedCount = 0;
    var objSel = document.getElementById(GetDestCityClientId());
    SelectTown(objSel.options[objSel.selectedIndex].value, 0);
    SetCountrySelectMode(false);
    if (selectedCount < 2) {
        selectedCount++;
    }
    if (isEC_HP)
        document.getElementById("cont_info").style.display = "none";
    CheckShowPrice();
}
function ChangeSrcTown() {
    logCall("ChangeSrcTown", arguments);
    selectedCount = 1;
    var objSel = document.getElementById(GetOriginCityClientId());
    if (isEC_HP)
        document.getElementById("cont_info").style.display = "none";
    SelectTown(objSel.options[objSel.selectedIndex].value, 1);
    SetCountrySelectMode(false);
    if (selectedCount < 2) {
        selectedCount++;
    }
    CheckShowPrice();
}

function DestTownsSelect() {
    logCall("DestTownsSelect", arguments);
    selectedCount = 0;
    var objSel = document.getElementById(GetDestCountryClientId());
    SetTownSelectMode(selectedCount == 0, objSel.options[objSel.selectedIndex].value);
}

function fitMap( map, markers, zoomChange ) {
    logCall("fitMap", arguments);
    if (map == null)
        return;
   var bounds = new GLatLngBounds();
   for (var i=0; i< markers.length; i++) {
      bounds.extend(markers[i].marker.getLatLng());
   }
   if (markers.length > 1) {
       var zoom = map.getBoundsZoomLevel(bounds);
       if (markers.length == 2 && zoom > 1) {
           zoom--;
       }
       else {
        if (zoomChange < 0) {
            zoom += zoomChange;
        }
       }
       map.setZoom(zoom);
   }
   else {
     map.setZoom(10);
   }
   map.setCenter(bounds.getCenter());
}

function ShowWorld(isDst) {
//    if (map == null)
//        return;
    if (dstMarkers == null) {
        dstMarkers = 1;
        ProgrLoad(true);
        GDownloadUrl(format("coords.aspx?world=1&src={0}&isEC_HP={1}{2}", selectedCount, isEC_HP ? 1 : 0, ecSessionId()), function(data, responseCode) {
            // To ensure against HTTP errors that result in null or bad data,
            // always check status code is equal to 200 before processing the data
            if (responseCode == 200) {
                var xml = GXml.parse(data);
                var markers = xml.documentElement.getElementsByTagName("country");
                //ClearMarkers();

                //mymarkers = new Array(markers.length);
                //mymarkersId = new Array(markers.length);
                var iSrc = 0;
                var iDst = 0;
                for (var i = 0; i < markers.length; i++) {
                    if (markers[i].getAttribute("issrc") == "1") {
                        iSrc++;
                    }
                    if (markers[i].getAttribute("isdst") == "1") {
                        iDst++;
                    }
                }
                srcMarkers = new Array(iSrc);
                dstMarkers = new Array(iDst);
                srcFullMarkers = new Array(iSrc);

                if (!isEC_HP) {
                    var selDst = document.getElementById(GetDestCountryClientId());
                    selDst.options.length = 0;
                    var selSrc = document.getElementById(GetOriginStateClientId());
                    selSrc.options.length = 0;
                    selDst.options[0] = new Option("Destination (Ship to)", 0);
                    selSrc.options[0] = new Option("Filter by State", 0);
                }

                iSrc = 0;
                iDst = 0;

                for (var i = 0; i < markers.length; i++) {
                    var name = markers[i].getAttribute("name");
                    var id = markers[i].getAttribute("id");
                    var point = new GLatLng(
                                parseFloat(markers[i].getAttribute("lat")),
                                parseFloat(markers[i].getAttribute("lng"))
                             );


                    if (markers[i].getAttribute("issrc") == "1") {
                        srcMarkers[iSrc] = new Object();
                        srcMarkers[iSrc].marker = createMarker(point, iSrc, 1, name, 1, 0);
                        srcMarkers[iSrc].id = id;
                        if (!isEC_HP)
                            selSrc.options[iSrc + 1] = new Option(name, id);
                        if (map != null) {
                            map.addOverlay(srcMarkers[iSrc].marker);
                        }
                        
                        srcFullMarkers[iSrc] = new Object();
                        srcFullMarkers[iSrc].marker = createMarker(point, iSrc, 1, name, 1, 0);
                        srcFullMarkers[iSrc].id = id;
                        srcFullMarkers[iSrc].name = name;
                        
                        iSrc++;
                    }
                    if (markers[i].getAttribute("isdst") == "1") {
                        dstMarkers[iDst] = new Object();
                        dstMarkers[iDst].marker = createMarker(point, iDst, 1, name, markers[i].getAttribute("nonclickable") == "1" ? 2 : 1, 0);
                        dstMarkers[iDst].marker.hide();
                        dstMarkers[iDst].id = id;
                        if (!isEC_HP)
                            selDst.options[iDst + 1] = new Option(name, id);
                        if (map != null) {
                            map.addOverlay(dstMarkers[iDst].marker);
                        }
                        iDst++;
                    }


                }
                if (map != null) {
                    map.setCenter(new GLatLng(worldLat, worldLng), worldZoom);
                }

                if (srcMarkers) {
                    ShowMarkers(isDstActive != 1, srcMarkers);
                    ShowMarkers(isDstActive == 1, dstMarkers);
                }
            } else if (responseCode == -1) {
                alert("Data request timed out. Please try later.");
            } else {
                alertAjaxError();
            }
            ProgrLoad(false);
             if (presel_c > 0)
            {
                SelectCountry(presel_c);
                presel_c = 0;
            }
        });
    }

    if (srcMarkers) {
        ShowMarkers(isDstActive != 1, srcMarkers);
        ShowMarkers(isDstActive == 1, dstMarkers);
    }
    else {
        if (map != null) {
            map.setCenter(new GLatLng(worldLat, worldLng), worldZoom);
        }
    }


}
function ShowMarkers(value, arr) {
    if (arr == null)
        return;
    for (var g = 0; g < arr.length; g++) {
        if (value) {
            arr[g].marker.show();
        }
        else {
            arr[g].marker.hide();
        }
    }
    if (value) {
        fitMap(map, arr, 0);
    }
}

function ClearMarkers() {
    if (townMarkers) {
        for (var i = 0; i < townMarkers.length; i++) {
            if (townMarkers[i] && map != null) {
                map.removeOverlay(townMarkers[i].marker);
            }
        }
        townMarkers = null;
    }
}
function HideMarkers() {
    if (townMarkers) {
        for (var i = 0; i < townMarkers.length; i++) {
            if (townMarkers[i]) {
                townMarkers[i].marker.hide();
            }
        }
    }
}
function SelectById(elementId, id, name) {
    logCall("SelectById", arguments);
    var el = document.getElementById(elementId);
    if (el) {
        for (var i = 0; i < el.options.length; i++) {
            if (el.options[i].value == id || el.options[i].text == name) {
                el.options[i].selected = true;
            }
            else {
                el.options[i].selected = false;
            }
        }
    }
}
function SelectTown(townId, selectedIdx) {
    logCall("SelectTown", arguments);
    if (map == null)
        return;
    Clear2Anim();        
    var value = -1;
    document.getElementById("shp_img").style.display = "none";

    var p;
    var hint;
    if (selectedIdx == 0)
    {
        RemoveSelectedMarker(1);
    }
    if (townMarkers == null) {
    }
    else {
        for (var i = 0; i < townMarkers.length; i++) {
            if (!townMarkers[i])
                continue;
            if (townMarkers[i].id == townId) {
                value = i;
                break;
            }
        }
        if (value > -1) {
            p = townMarkers[value].marker.getPoint();
            hint = townMarkers[value].marker.getTitle();
        }
    }
    if (value < 0) {
        var townbuf;
        if (selectedIdx == 0) {
            townbuf = townsBufDst;
        }
        else {
            townbuf = townsBufSrc;
        }
        if (townbuf) {
            for (var i = 0; i < townbuf.length; i++) {
                if (townbuf[i]) {
                    if (townbuf[i].id == townId) {
                        p = new GLatLng(townbuf[i].lat, townbuf[i].lng);

                        hint = townbuf[i].name;

                        RemoveSelectedMarker(selectedIdx);

                        selectedMarkers[selectedIdx] = new Object();
                        selectedMarkers[selectedIdx].marker = createMarker(p, selectedIdx, 0, hint, 2, selectedIdx);
                        selectedMarkers[selectedIdx].id = townId;
                        selectedMarkers[selectedIdx].db_town_id = townbuf[i].db_town_id;
                        if (map != null) {
                            map.addOverlay(selectedMarkers[selectedIdx].marker);
                        }

                        break;
                    }
                }
            }
        }
        if (selectedIdx == 0) {
            CheckSteps(4);
        }

        return;
    }



    RemoveSelectedMarker(selectedIdx);

    selectedMarkers[selectedIdx] = new Object();
    selectedMarkers[selectedIdx].marker = createMarker(p, selectedIdx, 0, hint, 2, selectedIdx);
    selectedMarkers[selectedIdx].id = townId;
    selectedMarkers[selectedIdx].db_town_id = townMarkers[value].db_town_id;
    if (map != null) {
        map.addOverlay(selectedMarkers[selectedIdx].marker);
    }

    SelectById(isEC_HP ? (selectedCount == 0 ? GetDestCityClientId() : GetOriginCityClientId()) : ("selTown" + selectedCount), townId);

    if (selectedIdx == 1) {
        clearBkColorId(GetOriginCityClientId());
        clearBkColorId(GetDestCityClientId());
    }

    if (selectedIdx == 0 && selectedMarkers[1] == null) {
        clearBkColorId(GetDestCityClientId());
        showAnimColor(GetOriginCityClientId());
    }
   
    if (carsFlg)
    {
    }
    else {
        if (home1flg) {
            if (selectedMarkers[0] != null && selectedMarkers[1] != null) {
                var commType = GetSelectedId("selectCont");
                clearBkColorId(GetDestCityClientId());
                clearBkColorId(GetOriginCityClientId());
                if (commType == "start") {
                    showAnimColor("selectCont");
                }
            }
        }
        else {
            if (selectedMarkers[0] != null && selectedMarkers[1] != null) {
                var commType = GetSelectedId("cmtype");
                clearBkColorId(GetDestCityClientId());
                clearBkColorId(GetOriginCityClientId());
                if (commType == "start") {
                    showAnimColor("cmtype");
                }
            }
        }
    }
   
    if (selectedIdx == 0) {
        CheckSteps(4);
    }

    
    
}
function SelectCountry(countryId) {
    SetTownSelectMode(selectedCount == 0, countryId);
}
function RemoveSelectedMarker(idx) {
    if (selectedMarkers[idx] != null) {
        if (map != null) {
            map.removeOverlay(selectedMarkers[idx].marker);
        }
        selectedMarkers[idx] = null;
    }
}

function SetCountrySelectMode(isDst, isMarkerClick) {
    logCall("SetCountrySelectMode", arguments);
    HideMarkers();
    var idx = 0;
    
    if (!isEC_HP)
    {
        if (isDst) {
            isDstActive = 1;
            idx = 0;
            clearBkColorId(GetOriginCityClientId());
        }
        else {
            isDstActive = 0;
            idx = 1;
            clearBkColorId(GetDestCityClientId());
        }
    
        var i;
        for (i = idx + 1; i <= 1; i++) {
            document.getElementById("selLabel" + i).style.visibility = "hidden";
            document.getElementById("selTown" + i).style.visibility = "hidden";
            document.getElementById("selCountry" + i).style.visibility = "hidden";
            document.getElementById("selimage" + i).style.visibility = "hidden";
            document.getElementById("step" + i + "0").style.display = "none";
            document.getElementById("step" + i + "1").style.display = "none";
        }
        document.getElementById("selLabel" + idx).style.visibility = "";
        document.getElementById("selCountry" + idx).style.visibility = "";
        document.getElementById("step" + idx + "0").style.display = "";
        
        if (isDst) {
            document.getElementById("selTown" + idx).style.visibility = "hidden";
            document.getElementById("selimage" + idx).style.visibility = "hidden";
            document.getElementById("step" + idx + "1").style.display = "none";
        }
    }
    
    if (isDst) {
        ShowWorld(isDst);
    }
    else {
        if (selectedMarkers[1] == null) {
            ShowTowns(0, 0, null, isMarkerClick);
            if (!isEC_HP) // unnec and/or wrong for EC
            {
                document.getElementById(GetOriginCityClientId()).style.visibility = "";
                document.getElementById(getStepDomId("step11")).style.display = ""; // wrong for EC!
            }
        }
        else {
            ShowWorld(isDst);
        }
    }
    if (selectedMarkers[0] != null && selectedMarkers[1] != null) {
        ShowMarkers(false, srcMarkers);
        ShowMarkers(false, dstMarkers);
        //                GetDist();
        CheckSteps(3);
        fitMap(map, selectedMarkers, 0);
    }
    if (!isEC_HP && !isDst && selectedMarkers[1] == null) {
        document.getElementById('selCountry1').selectedIndex = 0;
    }
}

function getStepDomId(step)
{
    return (typeof ec_control_prefix != "undefined" ? ec_control_prefix() : "") + step;
}

function addRow(c1, c2, c3, c4, style_add, id) {
    return '<tr ' + style_add + '><td align="left">' + c1 + '</td><td align="center">' + c2 + '</td><td align="center">' + c3 + '</td><td' + (id == null ? '':' id="' + id + '"') + ' align="right">' + c4 + '</td></tr>'
}
function GoToBook() {
    var id1 = selectedMarkers[0].id
    var id2 = selectedMarkers[1].id;
    var contType = GetSelectedId("selectCont");
//    var cmType = GetSelectedId("cmtype");
    var num = document.getElementById("numCont").value;
    //    window.location = "book.aspx?id1=" + id1 + "&id2=" + id2 + "&ct=" + contType + "&n=" + num; // "&cmt=" + cmType

    document.getElementById("hid1").value = id1;
    document.getElementById("hid2").value = id2;
    document.getElementById("hcontType").value = contType;
    document.getElementById("hnum").value = num;
    
    document.forms[0].action = "book.aspx"
    document.forms[0].submit();
}
function hideDispl(el_name, visible) {
    document.getElementById(el_name).style.display = visible ? "" : "none";
}
function showim_a_b(visible) {
    if (!isEC_HP)
        hideDispl("img_a", visible);
    hideDispl("img_b", visible);
    var w = visible ? '50px' : '1px';
    document.getElementById("divi1").style.width = w;
    document.getElementById("divi2").style.width = w;

    hideDispl("dstinfo", visible);
    hideDispl("l_src", visible);
    hideDispl("dstinfo2", !visible);
    hideDispl("l_src2", !visible);
    hideDispl("impinfa", visible && !isEC_HP);
    hideDispl("impinfa2", !visible);
    hideDispl("lblbg1", visible);
    hideDispl("lblbg2", !visible);
    hideDispl("zipau", true);
    hideDispl("zipau1", false);
}

// ecDist is in US Land miles
function GetDist(ecDist, ecDistPrice, eCarGDir) {
    var id1 = selectedMarkers[0].id
    var id2 = selectedMarkers[1].id;
    var contType = isEC_HP ? document.getElementById("selectCont").selectedIndex : GetSelectedId("selectCont");
    var cmType = GetSelectedId("cmtype");
    var num = document.getElementById("numCont").value;
//    document.getElementById('testLabel').innerHTML = id1 + ' ' + id2;8
    document.getElementById("priceFinal").innerHTML = "";
    document.getElementById("l_src").innerHTML = "";
    document.getElementById("l_dst").innerHTML = "";
//zip
    document.getElementById("hCfsZip").value = "";
    document.getElementById("hPickupDist").value = "";
    document.getElementById("hPickupDistKm").value = "";
    var i;
    for (i = 1; i <= 3; i++) {
        hideDispl("tr_opt_a" + i, true);
    }
    //document.getElementById('img_b').src = "images/opt_b.gif";
    document.getElementById('divi1').style.width = '50px';
    document.getElementById('divi2').style.width = '50px';

    showim_a_b(true);
    
    
    hideDispl("spn_b", true);
    hideDispl("spn_b_zip", false);
    hideDispl("img_w", false);
    hideDispl("tr_opt_b", true && !isEC_HP); // do not show B option for EC
    hideDispl("impnote1", true);
    hideDispl("impnote2", false);
    hideDispl("impnote3", false);
    hideDispl("impnote3a", true);
    hideDispl("impnote2r", false);
    hideDispl("trbooka", true);
        
    clearDir();

    GDownloadUrl("calc.aspx?id1=" + id1 + "&id2=" + id2 + "&ct=" + contType + "&cmt=" + cmType + "&n=" + num + ecSessionId() + format("&ec_dist={0}&ec_dist_price={1}", ecDist, ecDistPrice),
      function(data, responseCode) {
          // To ensure against HTTP errors that result in null or bad data,
          // always check status code is equal to 200 before processing the data
          if (responseCode == 200) {
              var xml = GXml.parse(data);
              var markers = xml.documentElement.getElementsByTagName("town");

              var srcName = '';
              var dstName = '';
              for (var i = 0; i < townsBufSrc.length; i++) {
                  if (townsBufSrc[i]) {
                      if (townsBufSrc[i].id == id2) {
                          srcName = townsBufSrc[i].name;
                          break;
                      }
                  }
              }
              for (var i = 0; i < townsBufDst.length; i++) {
                  if (townsBufDst[i]) {
                      if (townsBufDst[i].id == id1) {
                          dstName = townsBufDst[i].name;
                          break;
                      }
                  }
              }
              dstName += ", " + GetSelectedText(GetDestCountryClientId());

              /*var detHeader = new Array(9);
              detHeader[0] = 'Ocean rate';
              detHeader[1] = 'BAF';
              detHeader[2] = 'DOC fee';
              detHeader[3] = 'SEO fee';
              detHeader[4] = 'MAR fee';
              detHeader[5] = 'Origin Inland Add-on';
              detHeader[6] = 'Service fee';
              detHeader[7] = 'SED';
              detHeader[8] = 'Destination Add-on';

            var detVal = new Array(9);
              detVal[0] = 'bsd';
              detVal[1] = 'baf';
              detVal[2] = 'doc';
              detVal[3] = 'seo';
              detVal[4] = 'mar';
              detVal[5] = 'originadd';
              detVal[6] = 'serfee';
              detVal[7] = 'sed';
              detVal[8] = 'destadd';*/

              var _zip = '';
              if (markers.length > 0) {
                  _zip = markers[0].getAttribute("zip");
              }

              if (_zip != null && _zip != "" // || isEC_HP
                ) {
                  document.getElementById("hCfsZip").value = _zip;
                  for (var g = 1; g <= 3; g++)
                      hideDispl("tr_opt_a" + g, false);
                  //                document.getElementById('img_b').src = "images/opt_a.gif";

                  hideDispl("spn_b", false);
                  hideDispl("spn_b_zip", true);
                  hideDispl("impnote2", true);
                  hideDispl("impnote1", false);
                  showim_a_b(false);
                  document.getElementById('l_src2').innerHTML = '';
              }

              for (var i = 0; i < markers.length; i++) {
                  var prc = markers[i].getAttribute("price");
                  if (prc != 0) {
                      document.getElementById("tablePrice").style.display = "";
                      document.getElementById("messagePrice").style.display = "none";
                      document.getElementById("priceFinal").innerHTML = "US$ " + markers[i].getAttribute("price");

                      var linkRefer = cmType;
                      var prevLinkReferText = '';
                      var idx = cmType.indexOf('(', 0);
                      if (idx > -1) {
                          var len = cmType.length - idx;
                          linkRefer = cmType.substr(idx, len);
                          prevLinkReferText = cmType.substring(0, idx - 1);
                      }
                      var contTypeStr = null;
                      if (isEC_HP)
                        switch (contType)
                        {
                            case 1: contTypeStr = "D20'"; break;
                            case 2: contTypeStr = "D40'"; break;
                            case 3: contTypeStr = "D40HC"; break;
                            default: throw "Unknown container type";
                        }
                      document.getElementById("priceFinal1").innerHTML = num + ' x ' 
                        + (isEC_HP ? contTypeStr : contType)
                        + ' ' + prevLinkReferText + ' <a href="ReferencesShippingSeaFreightUsa.aspx" target="_blank">' + linkRefer + '</a';
                      document.getElementById("priceFinalSrc").innerHTML = srcName + ', USA';
                      document.getElementById("priceFinalSrc1").innerHTML = srcName + ', USA';
                      document.getElementById("l_src").innerHTML = srcName + ', USA';
                      document.getElementById("l_dst").innerHTML = dstName;
                      var detTableHtml = addRow('Charge Name', 'Num', 'Rate/Min', 'US$', "style='background:#DDDDDD'");

                      for (var g = 0; g < detHeader.length; g++) {
                          var _detVal = markers[i].getAttribute(detVal[g]);
                          if (_detVal == "0" || !_detVal)
                              continue;
                          var _val = parseFloat(_detVal);
                          if (g < nSurchEveryCont) {
                              detTableHtml += addRow(detHeader[g], num, '$' + _val, '$' + num * _val, '');
                          }
                          else { // serfee and SED
                              detTableHtml += addRow(detHeader[g], '&nbsp;', '$' + _val, '$' + _val, '');
                          }
                      }
                      detTableHtml += addRow('Total', '&nbsp;', '&nbsp;', '$' + prc, "style='background:#DDDDDD'", 'priceDetFinal');
                      document.getElementById("priceDet").innerHTML = "<table class='calclabel' id='tabPriceDet'>" + detTableHtml + "</table>";
                      if (isEC_HP)
                          document.getElementById(get_ec_bsd_clientid()).value = markers[i].getAttribute("bsd");
                  }
                  else {
                      document.getElementById("tablePrice").style.display = "none";
                      document.getElementById("messagePrice").style.display = "";
                  }
                  break;
              } // for
              if (isEC_HP) {
                  dirEnable = true;
                  onGDirectionsLoad(eCarGDir);
                  showAjaxLoading('cont_info', false);
                  jQuery('#ec_price')[0].value = prc;
                  jQuery('#ec_serfee')[0].value = markers[i].getAttribute("serfee");
                  jQuery('#ec_sea_freight')[0].value = markers[i].getAttribute("bsd");
                  // when price XML is requested via calc.aspx, attrs with ECar dest/origin 5 digit IDs are added from ECar response
                  if (markers[i].getAttribute("ec_dest_code") != GetSelectedId(get_destcity_clientid()) || markers[i].getAttribute("ec_orig_code") != GetSelectedId(get_origincity_clientid()))
                        alert("Warning: destination/origin/price do not match");
              }
          } else if (responseCode == -1) {
              alert("Data request timed out. Please try later.");
          } else {
              alertAjaxError();
          }
      });   // GDownloadUrl
}
function SetTownSelectMode(isDst, countryId) {
    logCall("SetTownSelectMode", arguments);
    Clear2Anim();
    if (isDst) {
        selectedCount = 0;
    }
    else {
        selectedCount = 1;
    }

    var i;
    for (i = 0; i <= selectedCount; i++) {
        document.getElementById("selLabel" + i).style.visibility = "";
        document.getElementById("selTown" + i).style.visibility = "";
        document.getElementById("selCountry" + i).style.visibility = "";
        document.getElementById("selimage" + i).style.visibility = "";
        document.getElementById("step" + i + "0").style.display = "";
        document.getElementById("step" + i + "1").style.display = "";
        
    }
    ShowTowns(countryId, isDst);

}
function GetSelectedId(selId) {
    var objSel = document.getElementById(selId);
    return objSel.selectedIndex < 0 ? undefined : objSel.options[objSel.selectedIndex].value;
}
function GetSelectedText(selId) {
    var objSel = document.getElementById(selId);
    return objSel.options[objSel.selectedIndex].text;
}

var gFiringEcEvent = false;
function ShowTowns(countryId, isDst, ecCountryName, isMarkerClick) {
    logCall(_logCallFlg, "ShowTowns: " + gFiringEcEvent, arguments);
    if (map == null)
        return;
    if (!isEC_HP && isDst && (selectedMarkers[0] == null || selectedMarkers[1] == null)) {
        showAnimColor(GetDestCityClientId());
    }
        
    ShowMarkers(false, srcMarkers);
    ShowMarkers(false, dstMarkers);

    var setDestId = "&dstid=0";
    if (selectedMarkers[0] != null)
    {
        setDestId = "&dstid=" + selectedMarkers[0].id;
    }
    
    var req;
    if (isDst) {
        req = "country=" + countryId;
        if (presel_c > 0) {
            req += "&cnts=1";
            if (presel_ref > 0) {
                req += "&refcntr=1";
            }
            
        }
        
    }
    else {  //src
        if (countryId == 0) {
            req = "country=0";
        }
        else {
            req = "townstate=" + countryId;
        }
    }
    
    showAjaxLoading('tdload1', true);
    var addon = isEC_HP ? format("&isEC_HP=1&ec_country_name={0}&ec_region_id={1}{2}"/*&dstid={2}*/, ecCountryName, GetSelectedId(GetDestCountryClientId()).split('-')[0]/*, GetSelectedId(GetDestCityClientId()).split(',')[0]*/,  ecSessionId()) : "";
    GDownloadUrl("coords.aspx?" + req  + setDestId + addon, function(data, responseCode) {
        // To ensure against HTTP errors that result in null or bad data,
        // always check status code is equal to 200 before processing the data
        if (responseCode == 200) {
            var xml = GXml.parse(data);
            var markers = xml.documentElement.getElementsByTagName("town");


            ClearMarkers();
            townMarkers = new Array(markers.length-1);
            var idx = isDst ? 0 : 1;

            SelectById(isEC_HP ? (isDst ? GetDestCountryClientId() : GetOriginStateClientId()) : "selCountry" + idx, countryId, ecCountryName);
            if (!isEC_HP) {
                var objSel = document.getElementById(isEC_HP ? (isDst ? GetDestCityClientId() : GetOriginCityClientId()) : "selTown" + idx);
                objSel.style.visibility = "";
                objSel.options.length = 0;
                objSel.options[0] = new Option("Select Nearest City", 0);
                // todo:EC?
                document.getElementById("selimage" + idx).style.visibility = "";
                document.getElementById("step" + idx + "1").style.display = "";
            }

            var townsbuf;
            if (isDst) {
                townsBufDst = new Array(markers.length-1);
                townsbuf = townsBufDst;
            }
            else {
                townsBufSrc = new Array(markers.length-1);
                townsbuf = townsBufSrc;
            }
            var zoomChange = 0;
            for (var i = 0; i < markers.length; i++) {
                var point;

                if (i == 0) {
                    point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                                parseFloat(markers[i].getAttribute("lng")));
                    zoomChange = parseFloat(markers[i].getAttribute("zoom"));
                   // map.setCenter(point, zoom);
                    continue;
                }
                var name = markers[i].getAttribute("name");
                var id = markers[i].getAttribute("id");
                if (!isEC_HP)
                    objSel.options[i] = new Option(name, id);


                townsbuf[i - 1] = new Object();
                townsbuf[i - 1].name = name;                
                townsbuf[i - 1].id = id; // can be EC id
                townsbuf[i - 1].lat = parseFloat(markers[i].getAttribute("lat"));
                townsbuf[i - 1].lng = parseFloat(markers[i].getAttribute("lng"));
                townsbuf[i - 1].db_town_id = markers[i].getAttribute("db_town_id");
                if (!isDst && countryId == 0) {
                    townsbuf[i - 1].parentId = markers[i].getAttribute("parentid");
                }
                else {
                    townsbuf[i - 1].parentId = 0;
                }
                

                point = new GLatLng(townsbuf[i - 1].lat, townsbuf[i - 1].lng);
                townMarkers[i - 1] = new Object();
                townMarkers[i - 1].marker = createMarker(point, i - 1, 1, name, markers[i].getAttribute("nonclickable") == "1" ? 2 : 0);
                townMarkers[i - 1].db_town_id = townsbuf[i - 1].db_town_id;
                townMarkers[i - 1].id = id;
                if (map != null) {
                    map.addOverlay(townMarkers[i - 1].marker);
                }
            }
            if (!isDst && countryId == 0) {
                RebuildStateFilters();
            }
            if (!isEC_HP && objSel.options.length == 1)
            {
                objSel.options[0].text = "No Origin cities found";
                document.getElementById("step6").style.display = "none";
            }
            fitMap(map, townMarkers, zoomChange);
        } else if (responseCode == -1) {
            alert("Data request timed out. Please try later.");
        } else {
            alertAjaxError();
        }

        // if (!isEC_HP)
            showAjaxLoading('tdload1', false);
        // /*
        if (isEC_HP && isMarkerClick) {
            gFiringEcEvent = true;
            // args: countryId, isDst, ecCountryName : 195, 1, AUSTRALIA; 0, 0; AZ, 0 - for dest country/town & origin state DDL selections            
            var el = document.getElementById(isDst ? GetDestCountryClientId() : (countryId == '0' ? GetDestCityClientId() : GetOriginStateClientId));            
            if (document.all)
                el.fireEvent('onchange');
            else {
                var e = document.createEvent('HTMLEvents');
                e.initEvent('change', false, false);
                el.dispatchEvent(e);
            }
            // showAjaxLoading('tdload1', false); // trying to delay loader causes it to show infinite
            gFiringEcEvent = false;
        } // */        
    }); // GDownload URL
}

function alertAjaxError() {
    alert("Request resulted in error. " + isEC_HP ? " Please, refresh browser window (e.g., by hitting Ctrl+F5)." : "Check XML file is retrievable.");  
}

function ecSessionId()
{
    return typeof get_ec_sessionid_clientid != "undefined" ? ("&ec_session_id=" + document.getElementById(get_ec_sessionid_clientid()).value) : "";
}

function stateNYCFilter(townid, stateid) {
    if (townid == NYCTownID && NYCStates != null) {
        for (var i = 0; i < NYCStates.length; i++) {
            if (NYCStates[i] == stateid) {
                return true;
            }
            
        }
    }
    else
        return false;
}
function RebuildStateFilters()
{
    var selSrc = document.getElementById(GetOriginStateClientId());
    selSrc.options.length = 0;
    selSrc.options[0] = new Option("Filter by State", 0);
    var iSrc = 0;    
//    ClearMarkers();
    for (var i=0; i<srcFullMarkers.length; i++)
    {
        for (var g=0; g<townsBufSrc.length; g++)
        {
            if (townsBufSrc[g].parentId == srcFullMarkers[i].id || stateNYCFilter(townsBufSrc[g].id, srcFullMarkers[i].id)) {
                selSrc.options[iSrc + 1] = new Option(srcFullMarkers[i].name, srcFullMarkers[i].id);
//                map.addOverlay(srcFullMarkers[i].marker);
                iSrc++;
                break;
            }
        }
    }
    
    
}
function createMarker(point, number, isdefault, hint, isCountry, isSrc) {
    // new GIcon("http://www.housingmaps.com/mapfiles/marker.png")
    //isCountry = 1  - c, 0 - t, 2 - none

    if (!baseIcon1) {
        baseIcon1 = new GIcon();
        baseIcon1.shadow = "msmarker.shadow.png";
        baseIcon1.image = "red-dot.png";
        baseIcon1.iconSize = new GSize(32, 32);
        baseIcon1.shadowSize = new GSize(59, 32);
        baseIcon1.iconAnchor = new GPoint(15, 32);

        baseIconSrc = new GIcon();
        baseIconSrc.shadow = "msmarker.shadow.png";
        baseIconSrc.image = "blue-dot.png";
        baseIconSrc.iconSize = new GSize(32, 32);
        baseIconSrc.shadowSize = new GSize(59, 32);
        baseIconSrc.iconAnchor = new GPoint(15, 32);

        baseIconDst = new GIcon();
        baseIconDst.shadow = "msmarker.shadow.png";
        baseIconDst.image = "green-dot.png";
        baseIconDst.iconSize = new GSize(32, 32);
        baseIconDst.shadowSize = new GSize(59, 32);
        baseIconDst.iconAnchor = new GPoint(15, 32);

        baseIconNonClickable = new GIcon();
        baseIconNonClickable.shadow = "msmarker.shadow.png";
        baseIconNonClickable.image = "red-dot-crossed.png"; // "ltblue-dot.png";
        baseIconNonClickable.iconSize = new GSize(32, 32);
        baseIconNonClickable.shadowSize = new GSize(59, 32);
        baseIconNonClickable.iconAnchor = new GPoint(15, 32);
    }

    //            baseIcon.infoWindowAnchor = new GPoint(9, 2);
    //            baseIcon.infoShadowAnchor = new GPoint(18, 25);



    var marker = new GMarker(point);
    if (isdefault) {  // sel town or cnt
        markerOptions = { icon: isCountry == 2 ? baseIconNonClickable : baseIcon1, title: hint, clickable: isCountry != 2, hide: isCountry == 2 };
        marker = new GMarker(point, markerOptions);
        //                mymarkers[number] = marker;
        //                mymarkersId[number] = markerId;

    }
    else {
        markerOptions = { icon: isSrc ? baseIconSrc : baseIconDst, title: hint };
        marker = new GMarker(point, markerOptions);

        //                selectedMarkers[number] = marker;
        //                selectedMarkersId[number] = markerId;

    }



    //            marker.value = number;
    // if (!isEC_HP) // markers clicking could work bad for EC
        if (isCountry == 1) {
            GEvent.addListener(marker, "click", function() {
                markerCountryClick(number);
            });
        }
        else {
            if (isCountry == 0) {
                GEvent.addListener(marker, "click", function() {
                    markerTownClick(number);
                });
            }
        }
    return marker;
}

function initialize(refNum) {
    if (refNum > 0) {
        ShowWorld(1);
        return;
    }
    GoogleMap = 1;
    var needShowCntr = presel_c;
    gdir = null;
    
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        if (isEC_HP)
            gECarGDir = new google.maps.Directions(map); // it's safer to not to assign gECarGDir to gdir...
        map.setUIToDefault();

        gdir = new google.maps.Directions(map);
        google.maps.Event.addListener(gdir, "load", onGDirectionsLoad);         
        
        ShowWorld(1);
    }
    if (needShowCntr == 0) {
        SetCountrySelectMode(1);
    }
    else {
        SelectCountry(needShowCntr);
    }
}

function addCell(row, value, idx, align) {
    var cell1 = row.insertCell(idx);
    var element1 = document.createElement("label");
    element1.innerHTML = value;
    cell1.appendChild(element1);
    cell1.align = align;
}

function is_debug()
{
    return typeof is_debugging != "undefined" && is_debugging();
}

function finishOnGDirectionsLoad(dir) {
    setTimeout("clearDir()", 500);
    document.getElementById("step6").style.display = "";
    if (isEC_HP)
        dir.clear(); // eCarGDir may be undefined if dstPrice > 300...
}

function onGDirectionsLoad(dir) {
    if (!dirEnable) {
        setTimeout("clearDir()", 500);
        return;
    }
    document.getElementById("distance").innerHTML = dir.getDistance().meters;
    dirEnable = false;
    // show opt a + dist
    var dstPrice = parseInt(dir.getDistance().meters / 1609);
    if (dstPrice >= 0 && dstPrice != NaN) {
        document.getElementById("hPickupDistKm").value = dstPrice;
    }
    if (!is_debug() && dstPrice > 300) {
        dirEnable = true;
        stopDir(1);
        setTimeout("clearDir()", 500);
        if (gECarGDirPrevQueryStr != gECarGDirQueryStr)
            alert(format('Range of {0} mile(s) is too big for delivery', dstPrice));
            
        finishOnGDirectionsLoad(dir);
        return;
    }
    var dstMi = dstPrice;
    if (dstPrice > 200) {
        dstPrice = 1000 + (dstPrice - 200) * 5;
    }
    else {
        if (dstPrice > 100) {
            dstPrice = 600 + (dstPrice - 100) * 4; // 600..1000
        }
        else {
            dstPrice = 600;
        }
    }
    var g;
    for (g = 1; g <= 3; g++) {
        hideDispl("tr_opt_a" + g, true);
    }

    hideDispl("tr_opt_b", false);
    hideDispl("tr_opt_a2", false);
    hideDispl("tr_opt_a3", false);
    hideDispl("spn_b", true);

    var prc = document.getElementById("priceFinal").innerHTML; //US$ nnn
    var prc_new = parseInt(prc.substring(4), 10);
       //tabPriceDet
    var table = document.getElementById("tabPriceDet");

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount - 1);
    var numCont = parseInt(document.getElementById("numCont").value, 10);
    document.getElementById("hPickupDist").value = numCont * dstPrice;

    addCell(row, ' Container(s) delivery in ' + dstMi + ' mile(s)', 0, "left");
    addCell(row, numCont, 1, "center");
    addCell(row, '$' + dstPrice, 2, "center");
    addCell(row, '$' + (dstPrice * numCont), 3, "right");
    document.getElementById("priceFinal").innerHTML = "US$ " + (prc_new + dstPrice * numCont);
    document.getElementById("priceDetFinal").innerHTML = "$" + (prc_new + dstPrice * numCont);
    
    finishOnGDirectionsLoad(dir);
}
function getDir() {
    if (gdir == null)
        return;
    gdir.load("from: 97210 to: 98032", { preserveViewport: true });
    setTimeout("clearDir()", 300);
}
function getDstCfs() {
    if (gdir == null)
        return;
    var zipFrom = document.getElementById("puzip").value;
    var zipTo = document.getElementById("hCfsZip").value;

    if (zipFrom == "") {
        alert('Plase enter ZIP code');
        return;
    }
    hideDispl("spn_b", false);
    hideDispl("spn_b_zip", false);
    hideDispl("img_w", true);
    dirEnable = true;
    document.getElementById('l_src2').innerHTML = zipFrom;    
    //    var fromZip =
    gdir.load("from: " + zipFrom + " to: " + zipTo, { preserveViewport: true });
    setTimeout("stopDir()", 7000);
}
function stopDir(value) {
    if (!dirEnable)
        return;
    var _value = value;
    dirEnable = false;
    var is2 = document.getElementById("zipau1").style.display != "none";
    if (is2 && _value != 1) {
        _value = 1;
    }
    
    var g;
    for (g = 1; g <= 3; g++) {
        hideDispl("tr_opt_a" + g, true);
    }
    hideDispl("tr_opt_b", true && !isEC_HP);
    hideDispl("spn_b", true);
    hideDispl("spn_b_zip", false);
    hideDispl("img_w", false);
    hideDispl("impnote1", true);
    hideDispl("impnote2", false);
    showim_a_b(false);
    if (_value == 1) {
        hideDispl("impnote3", true);
        hideDispl("impnote3a", false);
        hideDispl("lblbg1", false);
        hideDispl("lblbg2", true);
        hideDispl("tr_opt_b", false);
        hideDispl("trbooka", false);
        if (!isEC_HP)
            hideDispl("step5", false); // AH: step5 is mentioned only here - could be a general non-ECar only bug
    }
    else {  // repeat
        hideDispl("impnote1", false);
        hideDispl("impnote3", false);
        hideDispl("impnote3a", true);
        hideDispl("impnote2r", true);
        hideDispl("zipau", false);
        hideDispl("zipau1", true);
        hideDispl("spn_b", false);
        hideDispl("spn_b_zip", true);
        hideDispl("trbooka", false);
    }
}
function clearDir() {
    logCall("clearDir");
    hideDispl("img_w", false); // ajax-loader1.gif (Wait)
    if (gdir != null) {
        gdir.clear();
    }
}


function f1() {
    listMenu = new FSMenu('listMenu', true, 'display', 'block', 'none');

    listMenu.animations[listMenu.animations.length] = FSMenu.animFade;
    listMenu.animations[listMenu.animations.length] = FSMenu.animClipDown;
    listMenu.animInSpeed = 0.2;
    listMenu.animOutSpeed = 0.2;

    arrow = null;
    if (document.createElement && document.documentElement) {
        arrow = document.createElement('span');
        arrow.appendChild(document.createTextNode('>'));
        arrow.className = 'subind';
    }
}
function mymenu() {
    f1();
    listMenu.activateMenu("listMenuRoot", arrow);
}
function myinitialize() {
    initialize();
    mymenu();
}
function getSty(elN) {
    return document.getElementById(elN).style;
}
function show_el(o, ctrlName) {
    getSty(ctrlName).display = (o == 1) ? 'block' : 'none';
}
function nt_h(o, ctrlName) {
    getSty(ctrlName).display = (o.value == 1) ? 'block' : 'none';
}
function nt_h1(o, ctrlName) {
    getSty(ctrlName).display = (o.value == 1) ? '' : 'none';
}

function sel_hide01(o, ctrlName) {
    getSty(ctrlName + o.value).display = 'none';
    getSty(ctrlName + (o.value == 1 ? "0" : "1")).display = 'block';    
}

// AH: unused
function animBkColor(elId, newcolor, interval) {
    var el1 = "#" + elId;
    $(el1).animate({
    backgroundColor: newcolor
    }, interval);
}

function timedCount() {
    var elId = elIdColor;
    var el = document.getElementById(elId);
    if (alternateAnimElIdColor != '') {
        SetBkColor(elIdColor, "White");
        SetBkColor(alternateAnimElIdColor, "White");
        if (cntColor == 0) {
            SetBkColor(alternateAnimElIdColor, color_blink);
            cntColor = 1;
        }
        else {
            SetBkColor(elIdColor, color_blink);
            cntColor = 0;
        }
        timerRunning = true;
        altCount++;
        if (altCount == 2) {
            timeColor = setTimeout("altPause()", 1700);
            altCount = 0;
        }
        else {
            timeColor = setTimeout("timedCount()", 1700);
        }
        return;
    }
    if (el) {
        if (cntColor == 0) {
            el.style.backgroundColor = color_blink;
            cntColor = 1;
        }
        else {
            el.style.backgroundColor = "White";
            cntColor = 0;
        }
    }
    timerRunning = true;
    timeColor = setTimeout("timedCount()", 1700);
}

function showAnimColor(elId) {
    if (elIdColor != "" && elIdColor != null) {
        clearBkColorId(elIdColor);
    }
    cntColor = 0;
    timerRunning = false;
    
    elIdColor = elId;
    timerRunning = true;
    timeColor = setTimeout("timedCount()", 100);
   // clearBkColor(elId);
}
function pause(millis) {
    var date = new Date();
    var curDate = null;

    do {
        curDate = new Date();
    }
    while (curDate - date < millis)
}
function clearBkColorId(elId) {
    if (timerRunning && (elIdColor == elId || elIdColor == "")) {
        clearTimeout(timeColor);
        elIdColor = "";
    }
    timerRunning = false;
    var el = document.getElementById(elId);
    if (el != null)
        el.style.backgroundColor = "White";
    else
        dummy();
}

function dummy() {
}

function SetBkColor(elId, newcolor) {
    var el = document.getElementById(elId);
    if (el) {
        setbkcl(el, newcolor);
    }
}
function setbkcl(el, newcolor) {
    el.style.backgroundColor = newcolor;
}

function clearBkColor(el) {
    if (timerRunning && el.id == elIdColor) {
        clearTimeout(timeColor);
        elIdColor = "";
    }
    timerRunning = false;

    el.style.backgroundColor = "White";
}
function em_valid(m) {
    if (!m)
        return false;
    if (m == '')
        return false;
    if (m.indexOf(',', 0) > -1)
        return false;
    var reg = /[\w-]+@([\w-]+\.)+[\w-]+/;
    if (!reg.test(m)) {
        return false;
    }
    return true;
}
function isBlank(val) {
    if (val == null) { return true; }
    for (var i = 0; i < val.length; i++) {
        if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n") && (val.charAt(i) != "\r")) { return false; }
    }
    return true;
}

function isInteger(val) {
    if (isBlank(val)) { return false; }
    for (var i = 0; i < val.length; i++) {
        if (!isDigit(val.charAt(i))) { return false; }
    }
    return true;
}
function isDigit(num) {
    if (num.length > 1) { return false; }
    var string = "1234567890";
    if (string.indexOf(num) != -1) { return true; }
    return false;
}
function elHasClass(elName, classVal)
{
    var el = document.getElementById(elName);
    if (!el)
        return false;
    if (el.className == '' || !el.className) {
        return false;
    }
    var ar = el.className.split(" ");
    for (var i=0; i<ar.length; i++)
    {
        if (ar[i] == classVal)
            return true;
    }
    return false;
}
function Clear2Anim() {
    SetBkColor("cmtype", "White");
    alternateAnimElIdColor = '';
}
function altPause() {
    SetBkColor(elIdColor, "White");
    SetBkColor(alternateAnimElIdColor, "White");
    timeColor = setTimeout("timedCount()", 3400);
}

// /*
function showAjaxLoading(elId, turnOn) 
{ 
  logCall("showAjaxLoading", arguments);
  var loader = jQuery('#ajax_load_waiter');
  var el = null;
  if (!turnOn) {
    loader.hide();
    if (document.all)
        jQuery('#' + elId).css({ "visibility": "visible"});
    return;
  }
  var el = jQuery('#' + elId), pos = el.position();
  if (document.all)
    el.css({ "visibility": "hidden"});
  loader.css({ "left": pos.left + "px", "top": pos.top + "px", "width": el.width(), "height": el.height() }).show();  
} // */

