var TOTAL_MARKER = 200;
var current_offset = 0;
var dhtml = new Dhtml();
var ajax = new Ajax();
var map = null;
var gmarkers = [];
var atmaddressList = [];
var bounds = {};
var displayResult_html = '';
var recordCount = 0;
var selectedIndex = -1;
var currentInfowindowIndex = -1;
var geoCoderObj = null;
var addarr = [];
var panFlag = false;
var panLat = 0;
var panLng = 0;
var searchby = '';
var searchkey = '';
var routeaddB = '';
var routeaddA = '';
var SetBounds = true;
var searchlatitude = "";
var searchlongitude = "";
var NoResultMessage = '<table border="0" style="width: 100%; border: 0px solid #7d2231; padding: 5px; font-size: 12px; line-height: 14px; text-align: left; color: #7d2231;"><tr><td><img src="https://images.locatorsearch.com/locatorlite_error.gif" border="0" />&nbsp;&nbsp;Sorry, there are no locations within the map area.</td></tr></table>';
var NoAddessMessage = '<table border="0" style="width: 100%; border: 0px solid #7d2231; padding: 5px; font-size: 12px; line-height: 14px; text-align: left; color: #7d2231;"><tr><td><img src="https://images.locatorsearch.com/locatorlite_error.gif" border="0" />&nbsp;&nbsp;Address not found as entered. Please check your address and try again.</td></tr></table>';
var SendToPhoneLabelTxt = 'Send To :';
var SmsLabelTxt = 'SMS';
var EmailLabelTxt = 'Email';
var HoursLabelTxt = 'Hours';
var DirectionLabelTxt = 'Get Directions';
var DistLabelTxt = 'miles';
var TabGoBtnLabelTxt = 'Go';


var directionsService = new google.maps.DirectionsService();
var directionsDisplay = {};

function handleSubmit(e) {
    var code = e.keyCode;
    if (code == 13) {
        //document.getElementById('address').value='';document.getElementById('address').className='inputtextactive';
        searchByText();
    }
}

function resize() {
    dhtml.setBounds('sliderTopLeft', leftMargin, topMargin, null, null);
    dhtml.setBounds('sliderTopMiddle', parseInt(leftMargin, 10) + roundCornerImageWidth, topMargin, leftPanelWidth - parseInt(roundCornerImageWidth * 2, 10), null);
    dhtml.setBounds('sliderTopRight', parseInt(leftMargin, 10) + (leftPanelWidth - parseInt(roundCornerImageWidth, 10)), topMargin, null, null);

    dhtml.setBounds('sliderMiddle', leftMargin, topMargin + roundCornerImageHeight, leftPanelWidth - (borderWidth * 2), (leftPanelHeight - parseInt(roundCornerImageHeight * 2, 10)));

    dhtml.setBounds('sliderBottomLeft', leftMargin, topMargin + (leftPanelHeight - roundCornerImageHeight), null, null);
    dhtml.setBounds('sliderBottomMiddle', leftMargin + roundCornerImageWidth, topMargin + (leftPanelHeight - roundCornerImageHeight), leftPanelWidth - parseInt(roundCornerImageWidth * 2, 10), null);
    dhtml.setBounds('sliderBottomRight', leftMargin + (leftPanelWidth - parseInt(roundCornerImageWidth, 10)), topMargin + (leftPanelHeight - roundCornerImageHeight), null, null);


    dhtml.setBounds('topLeft', (leftMargin + leftPanelWidth + vspace), topMargin, null, null);
    dhtml.setBounds('topMiddle', (leftMargin + leftPanelWidth + vspace) + roundCornerImageWidth, topMargin, mapPanelWidth - (roundCornerImageWidth * 2), roundCornerImageHeight - 1);
    dhtml.setBounds('topRight', (leftMargin + leftPanelWidth + vspace) + mapPanelWidth - roundCornerImageWidth, topMargin, null, null);
    dhtml.setBounds('mapToolbar', (leftMargin + leftPanelWidth + vspace), (topMargin + roundCornerImageHeight), mapPanelWidth - 2, mapToolbarHeight);
    dhtml.setBounds('map', (leftMargin + leftPanelWidth + vspace), topMargin + roundCornerImageHeight + mapToolbarHeight + (borderWidth * 4), mapPanelWidth - 2, mapPanleHeight - ((roundCornerImageHeight * 2) + mapToolbarHeight + 4));

    dhtml.setBounds('progress', (leftMargin + leftPanelWidth + vspace) + 1, topMargin + roundCornerImageHeight + mapToolbarHeight + (borderWidth * 4), mapPanelWidth - 2, mapPanleHeight - ((roundCornerImageHeight * 2) + mapToolbarHeight + 4));

    dhtml.setBounds('bottomLeft', (leftMargin + leftPanelWidth + vspace), topMargin + mapPanleHeight - roundCornerImageHeight, null, null);
    dhtml.setBounds('bottomMiddle', (leftMargin + leftPanelWidth + vspace) + roundCornerImageWidth, topMargin + mapPanleHeight - roundCornerImageHeight, mapPanelWidth - (roundCornerImageWidth * 2), null);
    dhtml.setBounds('bottomRight', leftMargin + leftPanelWidth + vspace + mapPanelWidth - roundCornerImageWidth, topMargin + mapPanleHeight - roundCornerImageHeight, null, null);

    dhtml.setBounds('searchInput', leftMargin, 0, (leftPanelWidth - borderWidth * 3), searchInputHeight);
    //dhtml.setBounds('searchResult', leftMargin, 0, (leftPanelWidth - borderWidth * 3), (leftPanelHeight - ((roundCornerImageHeight * 2) + (sliderHeight * 3) + searchBoxHeight + (sliderSpace * 3) + searchResultHeight)));
    dhtml.setBounds('searchResult', leftMargin, 0, (leftPanelWidth - borderWidth * 3), leftPanelHeight - (searchInputHeight + (sliderHeight * 3) + searchBoxHeight));
    //dhtml.setBounds('directionResult', leftMargin, 0, (leftPanelWidth - borderWidth * 3), (leftPanelHeight - ((roundCornerImageHeight * 2) + (sliderHeight * 3) + searchBoxHeight + (sliderSpace * 3) + 5)));
    dhtml.setBounds('directionResult', leftMargin, 0, (leftPanelWidth - borderWidth * 3), leftPanelHeight - (searchInputHeight + (sliderHeight * 3) + searchBoxHeight + 5));
    //dhtml.setBounds('directionText', leftMargin, 0, null, (leftPanelHeight - ((roundCornerImageHeight * 2) + (sliderHeight * 3) + searchBoxHeight + 110)));
    dhtml.setBounds('directionText', leftMargin, 0, null, leftPanelHeight - (searchInputHeight + (sliderHeight * 3) + searchBoxHeight + 85));
}

function init() {

    // Set Onload Variables
    var i;
    var searchString = document.location.search;
    searchString = searchString.substring(1);
    var nvPairs = searchString.split("&");
    for (i = 0; i < nvPairs.length; i++) {
        var nvPair = nvPairs[i].split("=");
        var name = nvPair[0];
        var value = nvPair[1];

        if (nvPair[0] == "s") {
            searchby = nvPair[1] + '|';
        }

        if (nvPair[0] == "SearchKey") {
            searchkey = nvPair[1];
        }
    }

    // AutoSuggest Address Code
    var input = document.getElementById('address');
    var options = { types: ['geocode'] };

    autocomplete = new google.maps.places.Autocomplete(input, options);

    // Directions Auto Suggest - driveAdd
    var driveAdd = document.getElementById('driveAdd');
    autocomplete = new google.maps.places.Autocomplete(driveAdd, options);

    //document.getElementById('slider1').className = 'selectedSlider'
    if (parseInt(screenWidth, 10) > 0 && parseInt(screenHeight, 10) > 0) {
        document.getElementById('sliderMiddle').style.height = (parseInt(screenHeight, 10) - 145) + 'px'; //'650px';     // 1280 X 800;
        document.getElementById('searchInput').style.height = (parseInt(screenHeight, 10) - 238) + 'px'; //'562px';
        document.getElementById('searchResult').style.height = (parseInt(screenHeight, 10) - 277) + 'px'; //'522px';
        document.getElementById('directionText').style.height = (parseInt(screenHeight, 10) - 305) + 'px'; //'495px';
        document.getElementById('topMiddle').style.width = (parseInt(screenWidth, 10) - 280) + 'px'; //'1000px';
        document.getElementById('bottomMiddle').style.width = (parseInt(screenWidth, 10) - 280) + 'px'; //'1000px';
        document.getElementById('map').style.width = (parseInt(screenWidth, 10) - 264) + 'px'; //'1016px';
        document.getElementById('map').style.height = (parseInt(screenHeight, 10) - 167) + 'px'; //'653px';         
        mapPanelWidth = ((parseInt(screenWidth, 10) - leftMargin) - vspace) - leftPanelWidth - 20;
        mapPanleHeight = ((parseInt(screenHeight, 10) - topMargin) - mapToolbarHeight) - (roundCornerImageHeight * 2) - 80;
        leftPanelHeight = ((parseInt(screenHeight, 10) - topMargin) - (roundCornerImageHeight * 2)) - 100;
        resize();

        dhtml.hideElement('fullscreenMenu');
    } else {
        resize();
    }

    var mapOptions = {
        zoom: 13,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
    geoCoderObj = new google.maps.Geocoder();

    //initialize the directions service
    directionsDisplay = new google.maps.DirectionsRenderer();

    //var GeoBasedSearch=true;
    if (addTXT != null && addTXT.length > 0) {
        document.getElementById('address').value = addTXT;
        searchByText();
    } else {
        if (typeof GeoBasedSearch == 'undefined') {
            map.setCenter(new google.maps.LatLng(OnloadLatitude, OnloadLongitude), 13);
            findNear(map);
        } else {
            if (GeoBasedSearch != null && GeoBasedSearch) 
            {
                //var loc = google.loader.ClientLocation;
                
                //if (loc != null) {
                //    map.setCenter(new google.maps.LatLng(loc.latitude, loc.longitude), 12);
                //    findNear(map);
                //} else {
                    map.setCenter(new google.maps.LatLng(OnloadLatitude, OnloadLongitude), 13);
                    findNear(map);
               // }
            } else {
                map.setCenter(new google.maps.LatLng(OnloadLatitude, OnloadLongitude), 13);
                findNear(map);
            }
        }
    }

    google.maps.event.addListener(map, "dragend", function () {
        findNearPan(map);
    });

    if (parseInt(screenWidth, 10) > 0 && parseInt(screenHeight, 10) > 0) {
        // load old map data
        routeaddA = opener.routeaddA || '';
        routeaddB = opener.routeaddB || '';

        searchby = opener.searchby;
        if (parseInt(opener.addarr.length, 10) == 2) {
            addarr.push(new google.maps.LatLng(opener.addarr[0].lat(), opener.addarr[0].lng()));
            addarr.push(new google.maps.LatLng(opener.addarr[1].lat(), opener.addarr[1].lng()));
        }
        if (opener.panFlag) {
            ajax = new Ajax();
            var postContent = '';
            postContent += "lat" + "=" + opener.panLat + "&";
            postContent += "lng" + "=" + opener.panLng + "&";
            postContent += "searchby" + "=" + escape(searchby) + "&";

            ajax.post("GetItems.aspx", postContent, processSearchResult);
        } else {
            searchATM(opener.document.getElementById('address').value);
        }
    }

}

function prepareSearchBy() {
    var flag = true;
    var counter = 0;
    searchby = '';
    while (flag) 
    {
        obj = document.getElementById('searchby' + counter);
        if (obj != null && obj != 'undefined') 
        {
            if (obj.checked == true) 
            {
                searchby += obj.value + "|";
            }
        }
        else 
        {
            flag = false;
        }
        counter++;
    }

    if (searchby.length <= 0) 
    {
        flag = true;
        counter = 0;
        while (flag) 
        {
            obj = document.getElementById('searchby' + counter);
            if (obj != null && obj != 'undefined') 
            {
                searchby += obj.value + "|";
                //obj.checked = true; 
            }
            else 
            {
                flag = false;
            }
            counter++;
        }
    }
}

function searchATM(address) {
    dhtml.showElement('progress');
    panFlag = false;
    //addarr= new Array();
    dhtml.setText('driveSummary', '');
    dhtml.setText('directionText', '');
    prepareSearchBy();
    ajax = new Ajax();
    var postContent = '';
    postContent += "address" + "=" + escape(address) + "&";
    postContent += "lat" + "=" + searchlatitude + "&";
    postContent += "lng" + "=" + searchlongitude + "&";
    postContent += "searchby" + "=" + escape(searchby) + "&";
    ajax.post("GetItems.aspx", postContent, processSearchResult);
}

function OnClickSearch() 
{
    if (typeof OnCheckSearch == 'undefined') {
        prepareSearchBy();
        findNear(map);
    }   
}

function searchByText() {
    clearOverlays();
    SetBounds = true;
    var add = document.getElementById('address').value;
    geoCoderObj.geocode({
        address: add
    }, function (result, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coord = result[0].geometry.location;
            //var lat=coord[1];
            //var lng=coord[0];
            searchlatitude = coord.lat();
            searchlongitude = coord.lng();
            map.setCenter(coord, 13); // this is where the search takes place            
            searchATM(add);
        } else {
            //alert('Address not found as entered. Please check your address and try again.');
            dhtml.setText('searchResult', NoAddessMessage);
        }
    });
}

function processSearchResult() {
    var ready = ajax.isReady();
    if (ready) {
        response = ajax.response();
        //alert("Response : " +response);
        dhtml.hideElement('directionResult');
        displayResult_html = '';
        dhtml.setText('searchResult', displayResult_html);
        recordCount = 0;
        current_offset = 0;
        TOTAL_MARKER = 200;

        if (response != 'ERROR') {
            // var xmlDoc = request.responseXML;
            //alert(response);
            var xmlDoc = parseXml(response);
            var i;
            var j;
            // obtain the array of markers and loop through it
            if (xmlDoc != null && xmlDoc.documentElement != null && xmlDoc.documentElement.getElementsByTagName("marker") != null) {
                var markers = xmlDoc.documentElement.getElementsByTagName("marker");
                recordCount = markers.length;
                TOTAL_MARKER = markers.length; 
                for (i = 0; i < gmarkers.length; i++) {
                    if (gmarkers[i] != null && gmarkers[i] != 'undefined') {
                        gmarkers[i].setMap(null);
                    }
                }
                if (markers.length > 0) {
                    bounds = new google.maps.LatLngBounds();
                } else {
                    //alert('No result returned.');
                    displayResult_html = NoResultMessage;
                }
                gmarkers = [];
                atmaddressList = [];
                //alert(markers.length);
                for (i = 0; i < markers.length; i++) {
                    // obtain the attributes of each marker
                    var lat = parseFloat(markers[i].getAttribute("lat"));
                    var lng = parseFloat(markers[i].getAttribute("lng"));
                    var label = textValue(markers[i].getElementsByTagName("label")[0]);
                    var icon = markers[i].getAttribute("icon");
                    var listicon = markers[i].getAttribute("listicon");
                    var zIndex = "";
                    
                    // alert("point["+i+"] label="+label+":("+lat+", "+lng+")");
                    if (isNaN(lat) || isNaN(lng)) {
                        alert("bad point " + i);
                        continue;
                    }
                    var point = new google.maps.LatLng(lat, lng);
                    // get the tab info
                    tabInfo = markers[i].getElementsByTagName("tab");
                    //tabs = new Array();
                    var tabs = new InfoBubble();
                    if (tabInfo.length > 0) {
                        // alert("processing "+tabInfo.length+" tabs");
                        for (j = 0; j < tabInfo.length; j++) {
                            var tabLabel = textValue(tabInfo[j].getElementsByTagName("label")[0]);
                            var tabHtml = '';
                            if (j == 0) {
                                addressobj = new ATMAddress();
                                addressobj.setTitle(textValue(tabInfo[j].getElementsByTagName("title")[0]));
                                addressobj.setAdd1(textValue(tabInfo[j].getElementsByTagName("add1")[0]));
                                addressobj.setAdd2(textValue(tabInfo[j].getElementsByTagName("add2")[0]));
                                addressobj.setImageUrl(textValue(tabInfo[j].getElementsByTagName("ImageUrl")[0]));
                                addressobj.setWorkPhone(textValue(tabInfo[j].getElementsByTagName("workphone")[0]));
                                addressobj.setDistance(textValue(tabInfo[j].getElementsByTagName("distance")[0]));
                                addressobj.setATMNetworkid(textValue(tabInfo[j].getElementsByTagName("atmnetworkid")[0]));
                                addressobj.setzIndex(textValue(tabInfo[j].getElementsByTagName("zIndex")[0]));
                                zIndex = textValue(tabInfo[j].getElementsByTagName("zIndex")[0]);
                                atmaddressList[i] = addressobj;
                                tabHtml = prepareTabWindow(addressobj, i);
                            } else {
                                tabHtml = textValue(tabInfo[j].getElementsByTagName("contents")[0]);
                            }


                            // alert("point["+i+"] tab["+j+"] label="+tabLabel+", contents="+tabHtml);
                            if ((j == 0) && (tabInfo.length > 2)) { //  adjust the width so that the info window is large enough for this many tabs
                                tabHtml = '<div style="width:' + parseInt(tabInfo.length, 10) * 88 + 'px">' + tabHtml + '<\/div>';
                            }
                            tabs.addTab(tabLabel, tabHtml);
                        }
                    } else {
                        // alert("no tabs point "+i);
                        tabs.addTab("Nothing", markers[i].getAttribute("html"));
                    }
                    if (parseInt(recordCount, 10) <= parseInt(TOTAL_MARKER, 10)) {
                        TOTAL_MARKER = recordCount;
                    }
                    if (i == 0) {
                        displayResult_html = "<table width='100%' cellspacing='0' cellpadding='0' class='tbl'>";
                    }
                    // create the marker
                    var marker;
                    if (i < TOTAL_MARKER) {
                        marker = createTabbedMarker(point, label, tabs, icon, listicon, zIndex, true);
                    } else {
                        marker = createTabbedMarker(point, label, tabs, icon, listicon, zIndex, false);
                        displayResult_html += "</table>";
                    }

                    if (i < TOTAL_MARKER) {
                        bounds.extend(point);
                        marker.setMap(map);
                    }
                }
                if (markers.length > 0) {
                    centerAndZoomOnBounds(bounds);
                }
                dhtml.showElement('searchResultContent');
                if (StaticMessage.length > 0) {
                    displayResult_html = StaticMessage + displayResult_html;
                }
                dhtml.setText('searchResult', displayResult_html);
                //dhtml.hideElement('searchInput');
                //alert(recordCount % TOTAL_MARKER);
                if (parseInt(recordCount % TOTAL_MARKER, 10) > 0) {
                    total_page = parseInt(recordCount / TOTAL_MARKER, 10) + 1;
                } else {
                    total_page = parseInt(recordCount / TOTAL_MARKER, 10);
                }
                if (gmarkers.length > 0) {
                    dhtml.setText('pageText', "");
                } else {
                    dhtml.setText('pageText', "");
                }
            } else {
                alert('No result found');
                dhtml.setText('pageText', "");
            }
            showSearchResult();

            if (gmarkers.length > 0 && DefaultInfoPopUp != "False") {
                tempVal = addTXT.replace(/%20/g, " ");
                var x;
                for (x = 0; x < atmaddressList.length; x++) {
                    //BUG - missing if?
                    //tempVal.indexOf(atmaddressList[x].getAdd1() > -1)
                    if (tempVal.indexOf(atmaddressList[x].getAdd1()) > -1) {
                        markerClicked(x);
                        break;
                    }
                }
            }
        } else {
            alert("Error occured while getting result");
        }        
        try 
        {
            if (opener != null && opener.addarr != null && parseInt(opener.addarr.length) == 2) {
                findDirection(); 
            }
        }
        catch (err) {
        }
        dhtml.hideElement('progress');
    }
}

function prepareTabWindow(addobj, index) 
{
    var str = '';
    str += "<div class='wrapper'>";
    str += "<div class='title_column'>" + addobj.getTitle() + "</div>";
    if (addobj.getDistance() > 0) {
        str += "<div class='left_column'><span id='address__" + index + "'>" + addobj.getAdd1() + "<br>" + addobj.getAdd2() + "<br>" + addobj.getDistance() + " " + DistLabelTxt;
    } else {
        str += "<div class='left_column'><span id='address__" + index + "'>" + addobj.getAdd1() + "<br>" + addobj.getAdd2();
    }
    if (addobj.getWorkPhone() != null && addobj.getWorkPhone().length > 0) {
        str += "<br>Phone :" + addobj.getWorkPhone() + "</span></div>";
    } else {
        str += "</span></div>";
    }
    str += "<div class='rightcolumn'>" + addobj.getImageUrl() + "</div>";
    str += "<div class='one_column'>";
    str += "<a href='javascript:searchDirection(" + index + ");'>" + DirectionLabelTxt + "</a>";
    str += "</div>";
    str += "<div>";
    str += "<div class=\"one_column\"><input class=\"infoTextBox\" value=\"" + document.getElementById('address').value + "\" onclick=\"javascript:document.getElementById('infoadd__" + index + "').value=''\"; type=\"text\" id=\"infoadd__" + index + "\" size=\"30\"/> <input type=\"button\" class=\"GoBtn\" value=\"" + TabGoBtnLabelTxt + "\" onclick=\"searchDirection2('infoadd__" + index + "','" + index + "')\";/></div>";
    str += "</div>";
    str += "</div>";
    return str;
}

function createTabbedMarker(point, label, tabs, icon, listicon, zIndex, flag) {
    var shadow = new google.maps.MarkerImage('https://images.locatorsearch.com/shadow50.png', new google.maps.Size(37, 34), new google.maps.Point(0, 0), new google.maps.Point(11, 33));
    var marker = new google.maps.Marker({
        position: point,
        icon: icon,
        title: label.replace('<br>','\n'),
        zIndex: parseInt(zIndex)        
    });
    var marker_num = gmarkers.length;
    marker.marker_num = marker_num;
    marker.tabs = tabs;
    gmarkers[marker_num] = marker;

    google.maps.event.addListener(gmarkers[marker_num], 'click', function () {
        if (!gmarkers[marker_num].tabs.isOpen()) {
            openInfoWindow(marker_num);
            var i;
            for (i = 0; i < gmarkers.length; i++) {
                if (i == marker_num) {
                    document.getElementById('searchResult').scrollTop = document.getElementById('tablerow' + i).offsetTop;
                    document.getElementById('tablerow' + i).className = 'rowSelected';
                    document.getElementById('lineRow' + i).className = 'rowSelected';
                    document.getElementById('lineobj' + i).className = 'hlineSelected';
                    if (document.getElementById('lineRow' + (i - 1)) != null) {
                        document.getElementById('lineRow' + (i - 1)).className = 'rowSelected';
                        document.getElementById('lineobj' + (i - 1)).className = 'hlineSelected';
                    }
                } else {
                    if (document.getElementById('tablerow' + i) != null) {
                        document.getElementById('tablerow' + i).className = 'row';
                        document.getElementById('lineRow' + i).className = 'row';
                        document.getElementById('lineobj' + i).className = 'hline';
                    }
                }
            }

        }
    });
    
    // add a line to the sidebar html
    if (flag) {
        displayResult_html += "<tr class='row' id='tablerow" + marker_num + "'><td><img id='img" + marker_num + "' style='cursor: pointer;padding-left: 5px;' onclick='javascript:markerClicked(" + marker_num + ")' src='" + listicon + "'></td><td>" + prepareResultAddress(atmaddressList[marker_num], marker_num) + "</td></tr>";
        displayResult_html += "<tr id='lineRow" + marker_num + "'><td colspan='2'><hr id='lineobj" + marker_num + "' class='hline'></td></tr>";
    }
    return marker;
}

function prepareResultAddress(addobj, i) {
    var str = '';
    str += "<div id= 'resultAddress__" + i + "' style='cursor: pointer; padding-left: 5px;' onmouseout='markermouseout(" + i + ")' onclick='toggleAddress(" + i + ");javascript:markerClicked(" + i + ");'";
    str += "<div><b>" + addobj.getTitle() + "</b>";
    str += "<br/><span id='address__" + i + "'>" + addobj.getAdd1() + "<br>";
    str += addobj.getAdd2() + "</span><br>";
    if (addobj.getDistance() > 0) {
        str += addobj.getDistance() + " " + DistLabelTxt + "<br>";
    }
    str += SendToPhoneLabelTxt + "<a href=javascript:OpenSMSWindow('SMSTextMessage.aspx?Loc=" + parseInt(i + 1, 10) + "')><img src='images/smsphone.gif' border='0'>  " + SmsLabelTxt + "</a> | <a href=javascript:OpenEmailWindow('EmailMessage.aspx?Loc=" + parseInt(i + 1, 10) + "')><img src='https://images.locatorsearch.com/email.gif' border='0'> " + EmailLabelTxt + "</a><br/>";

    if (addobj.getATMNetworkid().length > 0) {
        str += "<a href='#' onclick='openHours(" + i + ");'>" + HoursLabelTxt + "</a> | " + "<a href='javascript:searchDirection(" + i + ");'>" + DirectionLabelTxt + "</a><br>";
    } else {
        str += "<a href='javascript:searchDirection(" + i + ");'>" + DirectionLabelTxt + "</a><br>";
    }
    str += "</div>";
    str += "</div>";

    return str;
}

function toggleAddress(index) {
    var i;
    if (dhtml.isVisible('extadd_' + index)) {
        dhtml.hideElement('extadd_' + index);
    } else {
        dhtml.showElement('extadd_' + index);
    }
    for (i = 0; i < gmarkers.length; i++) {
        if (i == index) {
            //document.getElementById('img'+i).focus();
            document.getElementById('tablerow' + i).className = 'rowSelected';
            document.getElementById('lineRow' + i).className = 'rowSelected';
            document.getElementById('lineobj' + i).className = 'hlineSelected';
            if (document.getElementById('lineRow' + (i - 1)) != null) {
                document.getElementById('lineRow' + (i - 1)).className = 'rowSelected';
                document.getElementById('lineobj' + (i - 1)).className = 'hlineSelected';
            }
        } else {
            if (document.getElementById('tablerow' + i) != null) {
                document.getElementById('tablerow' + i).className = 'row';
                document.getElementById('lineRow' + i).className = 'row';
                document.getElementById('lineobj' + i).className = 'hline';
            }
        }
    }
}

function getAddressFromTab(htmlAdd) {
    var str = htmlAdd.substring(0, htmlAdd.indexOf('Distance:') - 8) + "</div>";
    //  alert(str);
    return str;

}

function markermouseout(index) {
    document.getElementById('resultAddress__' + index).className = '';
}

function markerClicked(index) {
    if (currentInfowindowIndex != index) {
        openInfoWindow(index);
    }
    document.getElementById('resultAddress__' + index).className = 'resultAddressImageOn';
    selectedIndex = index;
    dhtml.setText('driveToTxt', atmaddressList[index].getAdd1() + "," + atmaddressList[index].getAdd2());
    dhtml.showElement('driveInput');
}

function openHours(i) 
{
    openInfoWindow(i);
    gmarkers[i].tabs.setTabActive(2);
    return false;
}

function centerAndZoomOnBounds(bounds) {
    if (bounds != null && SetBounds != false) {
        map.fitBounds(bounds);
        var zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
            google.maps.event.removeListener(zoomChangeBoundsListener);
            if (this.getZoom()) {
                this.setZoom(this.getZoom());
            }
        });
        //map.setCenter(bounds.getCenter(center), map.getBoundsZoomLevel(bounds) + (parseInt(BoundsZoomLevel)));
    }
}

function next() {
    start = current_offset + TOTAL_MARKER;
    if (start >= recordCount) {
        //alert("You are at the end of records.");
    } else {

        if (parseInt(start,10) + parseInt(TOTAL_MARKER,10) < gmarkers.length) {
            end = parseInt(start,10) + parseInt(TOTAL_MARKER,10);
        } else {
            end = gmarkers.length;
        }
        prepareResult(start, end);
    }
}

function previous() {
    if (current_offset == 0) {
        // alert("You are at the begining of records.");
    } else {
        start = current_offset - TOTAL_MARKER;
        end = parseInt(start,10) + parseInt(TOTAL_MARKER,10);
        prepareResult(start, end);
    }
}

function prepareResult(start, end) {
    var i;
    clearOverlays();
    displayResult_html = '';
    dhtml.setText('searchResult', displayResult_html);
    displayResult_html = '<table cellspacing="0" cellpadding="0">';
    var bounds = new google.maps.LatLngBounds();
    for (i = 0; i < gmarkers.length; i++) {
        if (gmarkers[i] != null && gmarkers[i] != 'undefined') map.removeOverlay(gmarkers[i]);
    }
    for (i = start; i < end; i++) {
        //displayResult_html += "<tr class='row'><td><img style='cursor: pointer' onmouseclick='javascript:markerClicked(" + i + ")' src='" + gmarkers[i].getIcon().image + "'></td><td style='white-space: nowrap;'>" + prepareResultAddress(atmaddressList[i],i) + "</td></tr>";
        displayResult_html += "<tr class='row' id='tablerow" + i + "'><td><img id='img" + i + "' style='cursor: pointer;padding-left: 5px;' onclick='javascript:markerClicked(" + i + ")' src='" + gmarkers[i].getIcon().image + "'></td><td>" + prepareResultAddress(atmaddressList[i], i) + "</td></tr>";
        displayResult_html += "<tr id='lineRow" + i + "'><td colspan='2'><hr id='lineobj" + i + "' class='hline'></td></tr>";
        bounds.extend(gmarkers[i].getPosition());
        //marker = new GMarker(opener.gmarkers[i].getLatLng(),getIcon(opener.gmarkers[i].getIcon().image));
        map.addOverlay(gmarkers[i]);
        //map.addOverlay(marker);
    }
    displayResult_html += '</table>';
    dhtml.setText('searchResult', '');
    dhtml.setText('searchResult', displayResult_html);
    centerAndZoomOnBounds(bounds);
    dhtml.setText('pageText', " Showing " + (start + 1) + "-" + end + " of " + recordCount + " ");
    current_offset = start;
}



function findNear(map) {
    if (dhtml.isVisible('searchResultContent') || (dhtml.getText('directionText') == null || dhtml.getText('directionText').length <= 0)) {
        dhtml.showElement('progress');
        clearOverlays();
        dhtml.setText('driveSummary', '');
        dhtml.setText('directionText', '');
        SetBounds = true;

        var center = map.getCenter();

        var Latitude = center.lat();
        var Longitude = center.lng();


        panLat = Latitude;
        panLng = Longitude;
        panFlag = true;

        if (searchby.length == 0) {
            prepareSearchBy();
        }

        displayResult_html = '';
        ajax = new Ajax();
        var postContent = '';
        postContent += "lat" + "=" + Latitude + "&";
        postContent += "lng" + "=" + Longitude + "&";
        postContent += "searchby" + "=" + escape(searchby) + "&";
        postContent += "SearchKey" + "=" + escape(searchkey) + "&";
        ajax.post("GetItems.aspx", postContent, processSearchResult);
        addarr = [];
    }
}

function findNearPan(map) {
    if (dhtml.isVisible('searchResultContent') || (dhtml.getText('directionText') == null || dhtml.getText('directionText').length <= 0)) {
        dhtml.showElement('progress');
        clearOverlays();
        dhtml.setText('driveSummary', '');
        dhtml.setText('directionText', '');
        SetBounds = false;

        var center = map.getCenter();

        var Latitude = center.lat();
        var Longitude = center.lng();


        panLat = Latitude;
        panLng = Longitude;
        panFlag = true;

        prepareSearchBy();
        displayResult_html = '';
        ajax = new Ajax();
        var postContent = '';
        postContent += "lat" + "=" + Latitude + "&";
        postContent += "lng" + "=" + Longitude + "&";
        postContent += "searchby" + "=" + escape(searchby) + "&";
        ajax.post("GetItems.aspx", postContent, processSearchResult);

        addarr = [];
    }
}

function searchDirection(index) {
    document.getElementById('driveAdd').value = document.getElementById('address').value;
    selectedIndex = index;
    dhtml.setText('driveSummary', '');
    dhtml.setText('directionText', '');
    dhtml.hideElement('searchResultContent');
    dhtml.setText('driveToTxt', document.getElementById('address__' + index).innerHTML);
    dhtml.showElement('directionResult');
    dhtml.showElement('driveToFromContent');
    dhtml.showElement('driveInput');
}

function SetStartAddr(index) {

    selectedIndex = index;
    dhtml.setText('driveSummary', '');
    dhtml.setText('directionText', '');
    //dhtml.hideElement('searchResultContent');
    //dhtml.hideElement('searchInput');
    dhtml.setText('driveToTxt', document.getElementById('address__' + index).innerHTML);
    //dhtml.showElement('directionResult');
    //dhtml.showElement('driveToFromContent');
    //dhtml.showElement('driveInput');
}

function searchDirection2(objName, index) {
    dhtml.showElement('progress');
    showDirectionResult();
    selectedIndex = index;
    obj = document.getElementById(objName);
    dhtml.setText('driveSummary', '');
    dhtml.setText('directionText', '');
    dhtml.hideElement('searchResultContent');
    //    dhtml.hideElement('searchInput');
    dhtml.setText('driveToTxt', document.getElementById('address__' + index).innerHTML);
    //    dhtml.setText('driveAdd',document.getElementById(objName).value);
    document.getElementById('driveAdd').value = obj.value;
    dhtml.showElement('directionResult');
    dhtml.showElement('driveToFromContent');
    dhtml.showElement('driveInput');
    //    alert(document.getElementById(objName).value);
    geocode(document.getElementById(objName).value);
}

function searchDirectionFromTab() {
    add = document.getElementById('driveAdd').value;
    if (add != null && add.length > 0) {
        dhtml.showElement('progress');
        geocode(add);
    }
}

function geocode(address) {
    routeaddB = address;
    if (address != null && address.length > 0 && address != 'Start Address') {
        geoCoderObj = new google.maps.Geocoder();
        geoCoderObj.geocode({
            address: address
        }, function (result, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                addarr = [];
                var coord = result[0].geometry.location; //result.Placemark[0].Point.coordinates;
                var lat = coord[1];
                var lng = coord[0];
                routeaddA = atmaddressList[selectedIndex].getAdd1() + ", " + atmaddressList[selectedIndex].getAdd2();
                addarr.push(coord);
                addarr.push(gmarkers[selectedIndex].getPosition());

                findDirection();
            } else {
                alert('Invalid address');
                dhtml.hideElement('progress');
            }
        });
    } else {
        alert('Starting Address is required');
        dhtml.hideElement('progress');
    }
}

function findDirection() {
    if (routeaddA.indexOf('<br>') > 0) 
    {
        routeaddA = routeaddA.substring(0, routeaddA.indexOf('<br>'));
    }
    str = routeaddB + " @" + addarr[0] + " to " + routeaddA + "@" + addarr[1];
    
    var request = {
        //origin: routeaddB + " @" + addarr[0],
        //destination: routeaddA + "@" + addarr[1],
        origin: routeaddB,
        destination: routeaddA,
        //destination: new google.maps.LatLng(addarr[1].lat(), addarr[1].lng()),
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionText"));

            dhtml.hideElement('driveToFromContent');
            if (document.getElementById('address__' + selectedIndex) != null) {
                summaryTxt = 'Route Summary<br><b>From: </b>' + document.getElementById('driveAdd').value + '<br><b>To: </b>' + document.getElementById('address__' + selectedIndex).innerHTML;
                dhtml.setText('driveSummary', summaryTxt);
            } else {
                if (opener != null && opener.document.getElementById('driveSummary') != null) {
                    dhtml.setText('driveSummary', opener.document.getElementById('driveSummary').innerHTML);
                }
            }
            dhtml.showElement('driveSummary');
            dhtml.showElement('directionText');
            dhtml.hideElement('progress');
        } else {
            var reason = "Code " + status;
            if (reasons[status]) {
                reason = reasons[status];
            }
            alert("Failed to obtain directions, " + reason);
            dhtml.hideElement('progress');

        }
    });

    return;
}

function fullscreen() {
    params = 'width=' + screen.width;
    params += ', height=' + screen.height;
    params += ', top=0, left=0';
    //     params += ', fullscreen=yes';
    newwin = window.open('index.aspx?w=' + screen.width + '&h=' + screen.height, 'windowname4', params);
    if (window.focus) {
        newwin.focus();
    }
    return false;
}

function print() {
    params = 'width=600';
    params += ', height=600';
    if (navigator.appName == "Microsoft Internet Explorer") {
        params += ', top=0, left=0,scrollbars =1'
    } else if (navigator.appName == "Netscape") {
        params += ', top=0, left=0,scrollbars=yes'
    }

    newwin = window.open('Print.aspx', 'windowname5', params);
    if (window.focus) {
        newwin.focus();
    }
    return false;
}

//Open a new infowindow


function openInfoWindow(index) {
    if (currentInfowindowIndex > -1 && gmarkers[currentInfowindowIndex] && gmarkers[currentInfowindowIndex].tabs) {
        gmarkers[currentInfowindowIndex].tabs.close();
    }
    gmarkers[index].tabs.open(map, gmarkers[index]);
    currentInfowindowIndex = index;
}

// clear the map markers


function clearOverlays() {
    var i;
    if (gmarkers) {
        for (i in gmarkers) {
            gmarkers[i].setMap(null);
        }
    }
    if (currentInfowindowIndex > -1) {
        gmarkers[currentInfowindowIndex].tabs.close();
    }
    directionsDisplay.setMap(null);
    directionsDisplay.setPanel(null);
    gmarkers = [];
}

// Parses the given XML string and returns the parsed document in a
// DOM data structure. This function will return an empty DOM node if
// XML parsing is not supported in this browser.


function parseXml(str) {
    if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
    }

    if (typeof DOMParser != 'undefined') {
        return (new DOMParser()).parseFromString(str, 'text/xml');
    }

    return createElement('div', null);
}

// Returns the text value (i.e., only the plain text content) of the XML document fragment given in DOM representation.
// compatible with IE (innerText) & other browsers (textContent)


function textValue(str) {
    if (str) {
        return str.textContent || str.text || str.innerText || '';
    }
}
