var glb_Action;
var glb_Status;
var glb_NearestLabPage;
var glb_filterKey="";
var glb_TableName="";
var glb_response="";
var glb_DrivingPage="";
//*************************************Common functions*******************************************//

/// <summary>
/// <Name>readCookie</Name>  
/// <Purpose>To read data from cookie</Purpose>
/// <Input>Name of the cookie</Input>       
/// <Output>Data stored in the cookie</Output>  
/// </summary>
/// <param name="name"></param>
function readCookie(name)
{
    var ca = document.cookie.split(';');
    var nameEQ = name + "=";
    for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return "";
}

/// <summary>
/// <Name>Redirect</Name>
/// <Purpose>To redirect the page to specific url</Purpose>
/// <Input>URL name to be redirected</Input>
/// <Output>Redirected to the specified URL</Output>  
/// </summary>
/// <param name="url"></param>
function Redirect(url)
{
    window.location.href=url;
}

/// <summary>
/// <Name>loadActiveXObject</Name>
/// <Purpose>To retrive the servlet response using AJAX</Purpose>
/// <Input>URL to access the servlet and from where it is called</Input>
/// <Output>The function name where the response is processed</Output>  
/// </summary>
/// <param name="url"></param>
/// <param name="from"></param>
function loadActiveXObject(url,from)
{
    AjaxRequest.get(
    {
        'url':url
        ,
        'onSuccess':function(req){
            if(req.xmlHttpRequest.readyState==4)
            {
                if(from=="Preferences")
                    ResponseForPreferences(req.responseText);
                else if(from=="ApplyPreference")
                    alert(req.responseText);
                else if(from=="NearestLabs")
                    ResponseForNearestLabs(req.responseText);
                else if(from=="GetToAddress")
                    ResponseForToAddress(req.responseText);
                else if(from=="LoadLabDetails")
                    ResponseForLabDetails(req.responseText);
                else
                    Dummy();
            }
            else
                loadActiveXObject(url,from);
        }
        ,
        'onError':function(req){
            alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);
        }
    }
    );
}


/// <summary>
/// <Name>Dummy</Name>
/// <Purpose>Dummy function</Purpose>
/// <Input></Input>
/// <Output></Output>  
/// </summary>
function Dummy()
{}


/// <summary>
/// <Name>checkNull</Name>
/// <Purpose>In the response xml to check, whether the node data is null or not</Purpose>
/// <Input>Data in that node</Input>
/// <Output>Empty string or data</Output>  
/// </summary>
/// <param name="data"></param>
function checkNull(data)
{
    if(data=="null" || data==null || data=="" || data=="0")
        return "";
    else
        return data;
}

/// <summary>
/// <Name>CheckNullNode</Name>
/// <Purpose>In the response xml to check, whether the node exists or not</Purpose>
/// <Input>Data node</Input>
/// <Output>Empty string or data in the given node</Output>  
/// </summary>
/// <param name="dataNode"></param>
function CheckNullNode(dataNode)
{
    var val = "";
    if(dataNode.length > 0)
    {
        val = dataNode[0].nodeValue;
        return val;
    }
    else
        return val;
}

/// <summary>
/// <Name>getLatLon</Name>
/// <Purpose>To get Latitude and Longitude for the given address</Purpose>
/// <Input>Address to find the latitude and longitude</Input>
/// <Output>Response from google service</Output>  
/// </summary>
/// <param name="address"></param>
//
function getLatLon(address)
{
    if(GBrowserIsCompatible())
        geocoder = new GClientGeocoder();
    if (geocoder) {
        geocoder.getLatLng(
            address, processLatLon);
    }
}

/// <summary>
/// <Name>processLatLon</Name>
/// <Purpose>To assign the Latitude and Longitude in a hidden text field</Purpose>
/// <Input>Latitude and Longitude</Input>
/// <Output></Output>  
/// </summary>
/// <param name="point"></param>
function processLatLon(point)
{
    if (!point) {
        alert(address + " not found");
    } else {
        document.getElementById("txtLat").value = point.lat();
        document.getElementById("txtLon").value = point.lng();
        insertData();
    }
}

/// <summary>
/// <Name>validateAdmin</Name>
/// <Purpose>To call servlet through ajax, to check whether the user is authenticated or ot</Purpose>
/// <Input></Input>
/// <Output></Output>  
/// </summary>
function validateAdmin(from)
{
    AjaxRequest.get(
    {
        'url':"../Authentication?from=none"
        ,
        'onSuccess':function(req){
            ValidateUser(req.responseText,from);
        }
        ,
        'onError':function(req){
            alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);
        }
    }
    );
}

/// <summary>
/// <Name>ValidateUser</Name>
/// <Purpose>To check the user is authenticated or not from the response of servlet call</Purpose>
/// <Input></Input>
/// <Output>authenticated or not</Output>  
/// </summary>
function ValidateUser(responseTxt,fromPage)
{
    if(responseTxt=="true")
        authenticated=true;
    else
        authenticated=false;

    if(authenticated)
    {
        if(fromPage=="ActiveList")
            loadList("Active");
        else if(fromPage=="AddSleepLab")
            addNewSleepLab();
        else if(fromPage=="EditSleepLab")
            loadLabData();
        else if(fromPage=="Import")
            LoadDDlXMLFiles();
        else if(fromPage=="InactiveList")
            loadList("Inactive");
        else if(fromPage=="Preferences")
            loadPreferences();
        else if(fromPage=="SleepLabInfo")
            loadLabInfo();
    }
    else
        window.location.href="login.htm";
   
}

/// <summary>
/// <Name>setFocus</Name>
/// <Purpose>To set focus to the specified control</Purpose>
/// <Input>control name</Input>
/// <Output></Output>  
/// </summary>
/// <param name="ctrl"></param>
function setFocus(ctrl)
{
    document.getElementById(ctrl).focus();
}


/// <summary>
/// <Name>setChecked</Name>
/// <Purpose>To get the list of checked labs for inactivate, activate or edit</Purpose>
/// <Input>Sleep lab id</Input>
/// <Output>List of sleep lab ids</Output>  
/// </summary>
/// <param name="id"></param>
function setChecked(id)
{
    var find = -1;
    var t=document.getElementById("hId").value;
    find = t.indexOf(id+",");
    if(find == -1)
        document.getElementById("hId").value = document.getElementById("hId").value+id+",";
    else
    {
        t = t.replace(id+",","");
        document.getElementById("hId").value=t;
    }
}

//*************************************User Index page*******************************************//

/// <summary>
/// <Name>passSourceAddress</Name>
/// <Purpose>Redirect nearest lab page with the given source address</Purpose>
/// <Input>From address</Input>
/// <Output>Redirection to nearest labs page</Output>
/// </summary>
function passSourceAddress()
{
    var address1 = document.getElementById("txtAddress1").value;
    var address2 = document.getElementById("txtAddress2").value;
    var city = document.getElementById("txtCity").value;
    var state = document.getElementById("ddlState").value;
    var zip = document.getElementById("txtZIP").value;
    var distance = document.getElementById("ddlDistance").value;
    var address = "";
    address = trim(address1+" "+address2+" "+city+" "+state);
    document.cookie = "SourceAddress =" + address+ ";";
    document.cookie = "SourceZip=" + zip+ ";";

    if(state != null && state != "") {
        if((city == null || city == "") && (zip == null || zip == "")) {
            alert("No Center Found. Please enter a city or zip code and try your search again.");
            return;
        }
    }

    if(address != "" || zip != "")
    {
        var url = "./NearestSleepLabs.htm?";
        var pageUrl = url + "Address=" + address+ "&Zip="+zip+"&MDist="+distance+"&from=index";
        window.location.href = pageUrl;
    } else {
        alert("Please enter address.");
    }
}

//*************************************Nearest Labs page*******************************************//
function openWebsite(website)
{
  window.open(''+website);
}

/// <summary>
/// <Name>getAddressAndLatLon</Name>
/// <Purpose>To access the google service to retrieve the latitude and longitude for the source address given</Purpose>
/// <Input>Calling page</Input>
/// <Output>Response from google service</Output>
/// </summary>
/// <param name="sourcePage"></param>

function getAddressAndLatLon(sourcePage)
{
    glb_NearestLabPage=sourcePage;
    setFocus("txtSaddress");
    getSourceAddress(glb_NearestLabPage);
    getSourceLatLon(glb_NearestLabPage);
}

/// <summary>
/// <Name>getSourceAddress</Name>
/// <Purpose>To retrieve the source address from the query string</Purpose>
/// <Input>Calling page</Input>
/// <Output>Source address</Output>
/// </summary>
/// <param name="sourcePage"></param>
function getSourceAddress(sourcePage)
{
    glb_NearestLabPage=sourcePage;
    
    urlParam = window.location.search.substring(1).split("&");
    if(urlParam != "")
    {
        if(glb_NearestLabPage=='ResultPage')
        {
            address = readCookie("SourceAddress");
            zip = readCookie("SourceZip");
            mdist=parseURL(2,urlParam);
            from = parseURL(3,urlParam);
            document.getElementById("txtSaddress").value = address;
            document.getElementById("txtSzip").value = zip;
            document.getElementById("ddlDistance").value=mdist;
            onAction = from;
        }
        else
        {
            mdist = parseURL(0,urlParam);
            rowcount = parseURL(1,urlParam);
            document.getElementById("ddlDistance").value=mdist;
            onAction = "preview";
        }
    }
}

/// <summary>
/// <Name>parseURL</Name>
/// <Purpose>To retrieve the data from the query string</Purpose>
/// <Input>URL and the index of the parameter</Input>
/// <Output>Corresponding value</Output>
/// </summary>
/// <param name="index"></param>
/// <param name="urlParam"></param>
function parseURL(index,urlParam)
{
    var address = urlParam[index];
    var arrText = address.split("=");
    var text = arrText[1];
    return text;
}
 
/// <summary>
/// <Name>getSourceLatLon</Name>
/// <Purpose>To retrieve the latitude and longitude from google service</Purpose>
/// <Input>Address</Input>
/// <Output>Response from the google service</Output>
/// </summary>
/// <param name="sourcePage"></param>
function getSourceLatLon(sourcePage) {
    glb_NearestLabPage=sourcePage;
    address = document.getElementById("txtSaddress").value;
    zip = document.getElementById("txtSzip").value;
    if((address == "" && zip == "")||(address == null && zip == null))
    {
        alert("Please enter valid address.");
        sLat = 0;
        sLon = 0;
        ResponseForNearestLabs("<?xml version='1.0'?><SleepLabList></SleepLabList>");
    }
    else
    {
        if(sourcePage=="ResultPage")
        {
            document.cookie = "SourceAddress =" + address+ ";";
            document.cookie = "SourceZip=" + zip+ ";";
        }
        if(GBrowserIsCompatible())
            geocoder = new GClientGeocoder();
        if (geocoder) {
            geocoder.getLatLng(
                address+" "+zip, processSourceLatLon);
        }
    }
}

/// <summary>
/// <Name>processSourceLatLon</Name>
/// <Purpose>To retrieve the latitude and longitude from google response</Purpose>
/// <Input>Latitude and longitude object</Input>
/// <Output>Latitude and longitude</Output>
/// </summary>
/// <param name="point"></param>
function processSourceLatLon(point)
{
    if (!point) {
        alert(address+" "+zip+ " not found");
        sLat = 0;
        sLon = 0;
        ResponseForNearestLabs("<?xml version='1.0'?><SleepLabList></SleepLabList>");
    } else {
        sLat = point.lat();
        sLon = point.lng();
        loadNearestLabs();
    }
}

/// <summary>
/// <Name>loadNearestLabs</Name>
/// <Purpose>To access the servlet to retrieve the nearest labs address</Purpose>
/// <Input></Input>
/// <Output>Response from the servlet</Output>
/// </summary>
function loadNearestLabs()
{
    var url='';
    var dist = document.getElementById("ddlDistance").value;
    if(glb_NearestLabPage=='ResultPage')
        url = "./NearestLabsServlet?from=search&Lat="+sLat+"&Lon="+sLon+"&mDist="+dist+"&Address="+address+" &Zip="+zip+"&onAction="+onAction;
    else
        url="../NearestLabsServlet?from=search&Lat="+sLat+"&Lon="+sLon+"&mDist="+dist+"&rowcount="+rowcount+"&Address="+address+"&Zip="+zip+"&onAction="+onAction;
    loadActiveXObject(url, "NearestLabs");
}

/// <summary>
/// <Name>ResponseForNearestLabs</Name>
/// <Purpose>To retrieve the xml data from the servlet and to transform through xsl</Purpose>
/// <Input>Xml data</Input>
/// <Output>Nearest labs</Output>
/// </summary>
function ResponseForNearestLabs(resText)
{
    var xslFile="";
    if(glb_NearestLabPage=='ResultPage')
        xslFile="NearestSleepLabs.xsl";
    else
        xslFile="PreviewSleepLabs.xsl";
    new Transformation().setXml(resText).setXslt(xslFile).transform('Listoflabs');
    xmlDoc=getDomFromXml(resText);
    loadMap(xmlDoc);
}


/// <summary>
/// <Name>loadMap</Name>
/// <Purpose>To retrieve the map from the google service</Purpose>
/// <Input>Source and nearest labs address</Input>
/// <Output>Map</Output>
/// </summary>
function loadMap(xmlDoc)
{
    if(GBrowserIsCompatible())
    {
        map = new GMap(document.getElementById("map_canvas"));
        point = new GPoint(sLon, sLat);
        map.centerAndZoom(point,8);
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
    } else {
        alert("Browser is not compatible to load map.")
    }

    if(sLon!=0 && sLat!=0)
    {
        var path=getPath();
        var dLat;
        var dLon;
        var yellowIcon= new GIcon(G_DEFAULT_ICON, path+"marker_yellow.png");
        map.addOverlay(new GMarker(point,yellowIcon));
        
        var len = xmlDoc.getElementsByTagName("Latitude").length;
        if(len > 0)
        {
            mdist = document.getElementById("ddlDistance").value;
            for(var i=0; i<len; i++)
            {
                if(xmlDoc.getElementsByTagName("Latitude")[i].childNodes[0] != null)
                    dLat = xmlDoc.getElementsByTagName("Latitude")[i].childNodes[0].nodeValue;
                else
                    dLat = 0;

                if(xmlDoc.getElementsByTagName("Longitude")[i].childNodes[0] != null)
                    dLon = xmlDoc.getElementsByTagName("Longitude")[i].childNodes[0].nodeValue;
                else
                    dLon = 0;

                var latlng = new GPoint(dLon, dLat);
                var sid = CheckNullNode(xmlDoc.getElementsByTagName("Id")[i].childNodes);
                var dName = CheckNullNode(xmlDoc.getElementsByTagName("Name")[i].childNodes);
                var dAdd1 = CheckNullNode(xmlDoc.getElementsByTagName("Address1")[i].childNodes);
                var dAdd2 = CheckNullNode(xmlDoc.getElementsByTagName("Address2")[i].childNodes);
                var dCity = CheckNullNode(xmlDoc.getElementsByTagName("City")[i].childNodes);
                var dState = CheckNullNode(xmlDoc.getElementsByTagName("State")[i].childNodes);
                var dZip = CheckNullNode(xmlDoc.getElementsByTagName("Zip")[i].childNodes);
                var dPhone = CheckNullNode(xmlDoc.getElementsByTagName("Phone")[i].childNodes);
                var infoWindow="";
                if(dAdd2 != "")
                    infoWindow = dName+"<br>"+dAdd1+"<br>"+dAdd2+"<br>"+dCity+", "+dState+" - "+dZip;
                else
                    infoWindow = dName+"<br>"+dAdd1+"<br>"+dCity+", "+dState+" - "+dZip;
                map.addOverlay(createMarker(latlng,i,infoWindow));
            }
        }
        else {
            //alert("No center found.");
            alert("No results found. Please expand your search area and try your search again.");
        }
    }
}


/// <summary>
/// <Name>getPath</Name>
/// <Purpose>To retrieve the path for images</Purpose>
/// <Input>Page</Input>
/// <Output>Path</Output>
/// </summary>
function getPath()
{
    if(glb_NearestLabPage=='ResultPage')
        path="./images/";
    else
        path="../images/";
    return path;
}

/// <summary>
/// <Name>createMarker</Name>
/// <Purpose>To place the markers on the corresponding location</Purpose>
/// <Input>latitude, longitude, address and index </Input>
/// <Output>Marker</Output>
/// </summary>
/// <param name="point"></param>
/// <param name="index"></param>
/// <param name="dAddress"></param>
function createMarker(point, index, dAddress)
{
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    var letter = String.fromCharCode("A".charCodeAt(0) + index);
    var letteredIcon = new GIcon(baseIcon);
    var path=getPath();
    letteredIcon.image = path + "marker" + letter + ".png";
    markerOptions = {
        icon:letteredIcon
    };
    var marker = new GMarker(point, markerOptions);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(dAddress);
    });
    return marker;
}

/// <summary>
/// <Name>setAction</Name>
/// <Purpose>To specify which operation is performed</Purpose>
/// <Input></Input>
/// <Output></Output>
/// </summary>
function setAction()
{
    onAction = "clkSearch";
}

//*************************************Driving Direction page*******************************************//

/// <summary>
/// <Name>getFromToAddress</Name>
/// <Purpose>To retrieve the from and to address and to access the google map service for direction</Purpose>
/// <Input>Calling page</Input>
/// <Output>Response from google service</Output>
/// </summary>
/// <param name="from"></param>
function getFromToAddress(from) {
    if(from=="DirectionPage")
    {
        document.getElementById("txtFrom").readOnly = true;
        document.getElementById("txtTo").readOnly = true;
    }
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        loadDirections(from);
    }
}

/// <summary>
/// <Name>loadDirections</Name>
/// <Purpose>To retrieve source and destination address from the query string and to load direction</Purpose>
/// <Input>Calling page</Input>
/// <Output>Direction</Output>
/// </summary>
function loadDirections(from) {
    glb_DrivingPage=from;
    urlParam = window.location.search.substring(1).split("&");
    id=parseURL(0,urlParam);
    fromAddress=readCookie("SourceAddress")+" "+readCookie("SourceZip");
    if( glb_DrivingPage=="DirectionPage")
    {
        saddress=readCookie("SourceAddress");
        szip=readCookie("SourceZip");
        mdist=parseURL(1,urlParam);
        document.getElementById("txtFrom").value = fromAddress;
    }
    loadActiveXObject("./EditLabServlet?id="+id,"GetToAddress");
}


/// <summary>
/// <Name>backToList</Name>
/// <Purpose>To return back to the nearest labs result page</Purpose>
/// <Input>Calling page</Input>
/// <Output>Redirection to the nearest labs result page</Output>
/// </summary>
function backToList(from)
{
    try
    {
        var url = "./NearestSleepLabs.htm";
        var pageUrl = url + "?Address=" + saddress+ "&Zip="+szip +"&MDist="+mdist+"&from="+from;
        window.location.href = pageUrl;
    }
    catch(err)
    {
        alert("Error:"+err);
    }
}


/// <summary>
/// <Name>printViewOfDrivingDirection</Name>
/// <Purpose>To open window for printing purpose</Purpose>
/// <Input></Input>
/// <Output>Print view of direction page</Output>
/// </summary>
function printViewOfDrivingDirection()
{
    window.open("PrintDirection.htm?LabId="+id,"Print", "scrollbars=2,height=700,width=770,top=0,left=100");
}

/// <summary>
/// <Name>handleErrors</Name>
/// <Purpose>To handle errors on loading direction page</Purpose>
/// <Input></Input>
/// <Output>Error messages</Output>
/// </summary>
function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else alert("An unknown error occurred.");

}

/// <summary>
/// <Name>onGDirectionsLoad</Name>
/// <Purpose>Google function to do anything while loading the direction</Purpose>
/// <Input></Input>
/// <Output></Output>
/// </summary>
function onGDirectionsLoad(){
}


//*************************************Sleep Lab Details page*******************************************//

/// <summary>
/// <Name>loadLabDetails</Name>
/// <Purpose>To retrieve the details from the query string and asssign in to specific fields</Purpose>
/// <Input></Input>
/// <Output>Sleep lab details</Output>
/// </summary>
function loadLabDetails()
{
    urlParam = window.location.search.substring(1).split("&");
    var id=parseURL(0,urlParam);
    saddress=readCookie("SourceAddress");
    szip=readCookie("SourceZip");
    mdist=parseURL(1,urlParam);
    distance  = parseURL(2,urlParam);
    loadActiveXObject("./EditLabServlet?id="+id,"LoadLabDetails")
    drivingdirection = "<a href='DrivingDirections.htm?LabId="+id+"&MDist="+mdist+"'>Driving Directions</a>";
}

function idtfInformation()
{
    urlParam = window.location.search.substring(1).split("&");
    var id=parseURL(0,urlParam);
    saddress=readCookie("SourceAddress");
    szip=readCookie("SourceZip");
    mdist=parseURL(1,urlParam);
    distance  = parseURL(2,urlParam);
    name  = parseURL(3,urlParam);

    document.getElementById("tdLabName").innerHTML = name;
}


//*************************************Mobile page*******************************************//

/// <summary>
/// <Name>loadMobileDetails</Name>
/// <Purpose>To retrieve the details from the query string and asssign in to specific fields</Purpose>
/// <Input></Input>
/// <Output>Message for mobile</Output>
/// </summary>

function loadMobileDetails()
{
    urlParam = window.location.search.substring(1).split("&");
    var id = parseURL(0,urlParam);
    var cookieName = "Mobile"+id;
    var labAddress = readCookie(cookieName);
    saddress = readCookie("SourceAddress");
    szip= readCookie("SourceZip");
    mdist=parseURL(1,urlParam);
   
    document.getElementById("txtLabDetails").value = labAddress;
}

/// <summary>
/// <Name>trim</Name>
/// <Purpose>To remove the right left white spaces in a string</Purpose>
/// <Input>Soruce string</Input>
/// <Output>String after removing white spaces</Output>
/// </summary>
/// <param name="s"></param>
function trim(s)
{
    var trimmed = s.replace(/^\s+|\s+$/g, '') ;
    if(trimmed==null || trimmed=="")
        trimmed="";
    return trimmed;
}


/// <summary>
/// <Name>getDomFromXml</Name>
/// <Purpose>To return the xml string as dom object</Purpose>
/// <Input>Xml string</Input>
/// <Output>Dom object</Output>
/// </summary>
/// <param name="xml"></param>
function getDomFromXml(xml) {

    if (typeof ActiveXObject != 'undefined') {
        var dom = new ActiveXObject("Microsoft.XMLDOM");
        dom.async = false;
        dom.loadXML(xml);
    }
    else {
        parser = new DOMParser();
        dom = parser.parseFromString(xml, "text/xml");
    }
    return dom;
}


/// <summary>
/// <Name>ResponseForToAddress</Name>
/// <Purpose>To load the driving direction by getting the 'To address' from the response</Purpose>
/// <Input>Response text</Input>
/// <Output>Driving direction</Output>
/// </summary>
/// <param name="responseTxt"></param>
function ResponseForToAddress(responseTxt)
{
    xmlDoc=getDomFromXml(responseTxt);

    var add1=checkNull(xmlDoc.getElementsByTagName("Address1")[0].childNodes[0].nodeValue);
    var add2 = checkNull(xmlDoc.getElementsByTagName("Address2")[0].childNodes[0].nodeValue);
    var city = checkNull(xmlDoc.getElementsByTagName("City")[0].childNodes[0].nodeValue);
    var state = checkNull(xmlDoc.getElementsByTagName("State")[0].childNodes[0].nodeValue);
    var zip = checkNull(xmlDoc.getElementsByTagName("Zip")[0].childNodes[0].nodeValue);
    var add=add1+" "+add2+" "+city+" "+state+" "+zip;
    if(glb_DrivingPage=="DirectionPage")
        document.getElementById("txtTo").value=add;
    toAddress=add;
    var locale = "en_US";
    gdir.load("from: " + fromAddress + " to: " + toAddress,
    {
        "locale": locale
    });
}


/// <summary>
/// <Name>ResponseForLabDetails</Name>
/// <Purpose>To load the lab details from the response text</Purpose>
/// <Input>Response text</Input>
/// <Output>Lab details</Output>
/// </summary>
/// <param name="responseTxt"></param>
function ResponseForLabDetails(responseTxt)
{
    xmlDoc=getDomFromXml(responseTxt);
    document.getElementById("tdLabName").innerHTML = checkNull(xmlDoc.getElementsByTagName("Name")[0].childNodes[0].nodeValue);
    var tAdd1= checkNull(xmlDoc.getElementsByTagName("Address1")[0].childNodes[0].nodeValue);
    var tAdd2=checkNull(xmlDoc.getElementsByTagName("Address2")[0].childNodes[0].nodeValue);
    var tCity=checkNull(xmlDoc.getElementsByTagName("City")[0].childNodes[0].nodeValue);
    var tState=checkNull(xmlDoc.getElementsByTagName("State")[0].childNodes[0].nodeValue);
    var tZip=checkNull(xmlDoc.getElementsByTagName("Zip")[0].childNodes[0].nodeValue);
    if(tAdd2!="")
        address=tAdd1+",<br>"+tAdd2+",<br>"+tCity+", "+tState+" - "+tZip;
    else
        address=tAdd1+",<br>"+tCity+", "+tState+" - "+tZip;
    document.getElementById("tdAddress").innerHTML = address;
    document.getElementById("tdPhone").innerHTML = checkNull(xmlDoc.getElementsByTagName("Phone")[0].childNodes[0].nodeValue);
    var website=checkNull(xmlDoc.getElementsByTagName("Website")[0].childNodes[0].nodeValue);
    document.getElementById("tdWebsite").innerHTML = "<a href =javascript:openWebsite('http://"+website+"')>"+website+"</a>";
    document.getElementById("tdAccrediation").innerHTML = checkNull(xmlDoc.getElementsByTagName("Accreditation")[0].childNodes[0].nodeValue);
   // document.getElementById("tdHomeSleepTest").innerHTML = checkNull(xmlDoc.getElementsByTagName("HomeSleepTest")[0].childNodes[0].nodeValue);
    document.getElementById("tdInsurance").innerHTML = checkNull(xmlDoc.getElementsByTagName("Insurance")[0].childNodes[0].nodeValue);
    document.getElementById("tdDistance").innerHTML = distance+" miles";
    document.getElementById("tdDrivingDirection").innerHTML = drivingdirection;
}

function sendMail()
{
    var from=document.getElementById("txtFrom").value;
    var message=document.getElementById("txtFeedBack").value;
    alert("Feedback sent.");

}
