// Javascript functions used by LocalService pages
// www.edmunds.com/local.html, www.edmunds.com/locallisting.html

var gJsonListing;
var gSvcType = "";
var gZip = "";
var gCity = "";
var gState = "";
var gMake = "";
var firstTime = true;

var handleListingSuccess = function (o) {
	
    //alert(o.responseText);
    if (o.responseText !== undefined) {
        var jsonObj;
        try { 
             gJsonListing = eval('('+ o.responseText + ')');
             var locationsArray = new Array();
             var locations = gJsonListing.location;
             if (!locations) {
                 alert('Your search did not return any results. Please try again');
             } else if(typeof locations == 'object') {
                if (locations[0] == undefined) {
                    locationsArray[0] = locations;
                } else {
                    locationsArray = locations;
                }
                gJsonListing.location = locationsArray;
             }
             
        } 
        catch (e) { 
          alert("Invalid Product Data");  
          if (YAHOO && YAHOO.example && YAHOO.example.container) YAHOO.example.container.wait.hide();          
        }
        redrawPage();     
        if (YAHOO && YAHOO.example && YAHOO.example.container) YAHOO.example.container.wait.hide();      
    }
};

var handleListingFailure = function (o) {
    if (o.responseText !== undefined) {
        alert("Please try again.");
    }
    if (YAHOO && YAHOO.example && YAHOO.example.container) YAHOO.example.container.wait.hide();   
};

var listingCallback = {success:handleListingSuccess, failure:handleListingFailure};
function getListingXML(serviceType, zip, city, state, make) {
    //document.body.style.cursor = "wait";
		// Show the Panel
	if (YAHOO && YAHOO.example && YAHOO.example.container) YAHOO.example.container.wait.show();
    if(serviceType == 'dealerships') {
      initializeGlobalVariables(serviceType, zip, city, state, make);
      if(zip != null && zip != '') {
        //var url = "http://localhost:7001/LocalSearchProxy/LocalSearchProxy.do?svcType=" + serviceType + "&zip=" + zip.replace(/\s+/g, "") + "&make=" + make;
        var url = "http://www.edmunds.com/apps/localsearch/LocationListing.do?svcType=" + serviceType + "&zip=" + zip.replace(/\s+/g, "") + "&make=" + make;
	    var request = YAHOO.util.Connect.asyncRequest("GET", url, listingCallback);
      } else {
        //var url = "http://localhost:7001/LocalSearchProxy/LocalSearchProxy.do?svcType=" + serviceType + "&city=" + city.replace(/\s+/g, "") + "&state=" + state.replace(/\s+/g, "") + "&make=" + make;
        var url = "http://www.edmunds.com/apps/localsearch/LocationListing.do?svcType=" + serviceType + "&city=" + city.replace(/\s+/g, "") + "&state=" + state.replace(/\s+/g, "") + "&make=" + make;
        var request = YAHOO.util.Connect.asyncRequest("GET", url, listingCallback);
      }
    } else {
        if(serviceType == 'repairshops') {
        initializeGlobalVariables(serviceType, zip, city, state, make);
        if(zip != null && zip != '') {
		      //var url = "http://localhost:7002/LocalSearchProxy/LocalSearchProxy.do?svcType=" + serviceType + "&zip=" + zip.replace(/\s+/g, "");
          	  var url = "http://www.edmunds.com/apps/localsearch/LocationListing.do?svcType=" + serviceType + "&zip=" + zip.replace(/\s+/g, "");
		      var request = YAHOO.util.Connect.asyncRequest("GET", url, listingCallback);
        } else {
          //var url = "http://localhost:7002/LocalSearchProxy/LocalSearchProxy.do?svcType=" + serviceType + "&city=" + city.replace(/\s+/g, "") + "&state=" + state.replace(/\s+/g, "");
          var url = "http://www.edmunds.com/apps/localsearch/LocationListing.do?svcType=" + serviceType + "&city=" + city.replace(/\s+/g, "") + "&state=" + state.replace(/\s+/g, "");
          var request = YAHOO.util.Connect.asyncRequest("GET", url, listingCallback);
        }
      } 
    }

}

function updateBoxAd(serviceType, make) {		
    var site = '';
    var page = '';
    var ubegin = '';
    //var uvalues = ':pos_1:zip_!ZIP:st_!STATE:cty_!COUNTYFIP:dma_!DMA:!EDMUNDSID|!EDW|!TIMESTAMP|!PAGEURL|!ZIP;';
    if(serviceType == 'dealerships') {
      if(make != null && make != '') {
          site = 'makemodel.new.dart';
          page = 'make='+ mm_getNiceName(make)+';';
          ubegin = 'make_' + mm_getNiceName(make)+':';
      } else {
          site = 'newcar.dart';
          page = 'page=newcar;';
          ubegin = 'page_newcar:';
      }
    } else {
        site = 'repairshop.dart';
        page = 'page=repair;';
        ubegin = 'page_repair:';
    }
    var size = g_AJAXHelper.ads.length;
    for (var i=0;i<size;i++) {
        var ad = g_AJAXHelper.ads[i];
        if(ad.cellId == 'localServiceListingDynamicBoxAd1') {
            ad.siteName = site;
            ad.targetParamsOnce = ad.targetParams.replace(/(page=[^;]+;)|(make=[^;]+;)/, page).replace(/(page_[^:]+:)|(make_[^:]+:)/,ubegin);
            ad.targetParams = ad.targetParamsOnce;
        }
    }
}

// This method will do all the steps which should happen on the page.
// It should be only called inside handleSuccess only
function redrawPage() {
  populateListingTab(gJsonListing);
  if (firstTime) {
      firstTime = false;
  } else {
      updateBoxAd(gSvcType, gMake);
      g_AJAXHelper.refreshAds();
  }
  clearOverlays();
  createLocationMarkers(gJsonListing);
  populateFromField(gJsonListing);
  displayMake(gSvcType);
  redrawLocalServiceListingTitle(gJsonListing);
}

function initializeGlobalVariables(svcType, zip, city, state, make) {
  gSvcType = svcType;
  gZip = zip;
  gCity = city;
  gState = state;
  gMake = make;
}
/*********************************************************************/
// Javascript functions for LocalServiceWidget Component
/*********************************************************************/
function callLocalServiceAjax() {
  var form = document.localServiceWidget;
  if(validateLocalServiceForm(form, form.serviceType, form.selectMake, form.searchText)) {
    var searchValue = form.searchText.value;
    var searchArray = searchValue.split(",", 2);
    if (searchArray.length == 1) {
      getListingXML(form.serviceType[form.serviceType.selectedIndex].value, searchArray[0], '', '', form.selectMake[form.selectMake.selectedIndex].value);
    }
    if (searchArray.length == 2) {
      getListingXML(form.serviceType[form.serviceType.selectedIndex].value, '', searchArray[0], searchArray[1], form.selectMake[form.selectMake.selectedIndex].value);
    }
    return;
  }
  return false;
}

function submitLocalServiceWidgetForm() {
  var form = document.localServiceWidget;
  if(validateLocalServiceForm(form, form.serviceType, form.selectMake, form.searchText)) {
    //form.submit();
    //use selectors: locallisting.[svcType].[make].[searchText].html
    var svcIdx = form.serviceType.selectedIndex;
    var sltrSvcType = form.serviceType.options[svcIdx].value;
    var makeIdx = form.selectMake.selectedIndex;
    var sltrMake = form.selectMake.options[makeIdx].value;
    var sltrSearchText = escape(form.searchText.value);
    window.location.href="http://www.edmunds.com/locallisting." + sltrSvcType + "." + sltrMake + "." + sltrSearchText + ".html";
    return true;
  }
  return false;
}

function clearSearchTextField(searchText) {
  if(searchText.value == '(eg: santa monica, ca or 90404)') {
    searchText.value = '';
  }
}

function populateLocalServiceWidgetFormFields() {
  var form = document.localServiceWidget;
  if(gSvcType == 'dealerships') {
    form.serviceType.selectedIndex = 1;
  }
  if(gSvcType == 'repairshops') {
    form.serviceType.selectedIndex = 2;
  }
}

function displayMake(serviceType) {
    var form = document.localServiceWidget;
    if (serviceType == "dealerships") {
        form.serviceType.selectedIndex = 1;
        form.selectMake.style.display = "block";
        var makeLabel = document.getElementById('makeLabel');
        makeLabel.style.display = "block";
    } else {
        if (serviceType == "repairshops") {
          form.serviceType.selectedIndex = 2;
        }
        form.selectMake.style.display = "none";
        var makeLabel = document.getElementById('makeLabel');
        makeLabel.style.display = "none";
    }
}

function redrawLocalServiceListingTitle(gJsonListing) {
    var svc_type = gJsonListing["@svcType"];
    var title = "Find ";
    if (svc_type == 'dealerships') {
        title += "Car Dealers in "
    } else if (svc_type == 'repairshops') {
        title += "Auto Repair Shops in "
    }
    title += gJsonListing.gCityName + ", " + gJsonListing.gStateFullName;
    if (gJsonListing.gZipCode != undefined && gJsonListing.gZipCode != "") {
      title += " " + gJsonListing.gZipCode;
    }
    var titleH1 = document.getElementById('localServiceListingTitleH1');
    titleH1.innerHTML = title;

    var seeMoreCityLink = document.getElementById("localServiceListingTitleHref");
    var linkText = "http://www.edmunds.com/" + svc_type + "/all/" + gJsonListing.gStateFullName.replace(/\s+/g, "") + "/index.html"
    seeMoreCityLink.setAttribute('href', linkText);
    seeMoreCityLink.innerHTML = "See more cities in " + gJsonListing.gStateFullName;
}

function validateLocalServiceForm(formName, serviceTypeSelect, makeSelectName, searchText) {
    if (serviceTypeSelect.selectedIndex == 0) {
        alert("Please Select a Service");
        serviceTypeSelect.focus();
        return false;
    }

    var searchValue = searchText.value;
    
    if(searchValue == '' || searchValue=='(eg: santa monica, ca or 90404)') {
        alert("Please enter valid city and state or ZIP code.\neg: santa monica, ca or 90404");
        searchText.focus();
        return false;
    }
    
    var searchArray = searchValue.split(",", 2);
    if (searchArray.length == 1) {
        var zip = searchArray[0];
        zip = zip.replace(/^\s+|\s+$/g, '');
        if (isNaN(zip)) {
            alert("Please enter city and state seperated by comma.\neg: santa monica, ca");
            searchText.focus();
            return false;
        } else if(zip.length != 5) {
            alert("Please enter valid city and state or ZIP code.\neg: santa monica, ca or 90404");
            searchText.focus();
            return false;
        }
        if (checkZipValidity(zip)) {
            searchText.value = zip.replace(/\s+/g, "");
            return true;
        } else {
            return false;
        }
    }
    if (searchArray.length == 2) {
        var city = searchArray[0];
        var state = searchArray[1];
      //if you reached here, then check if the city and state are valid.
        if (checkCityValidity(city, state)) {
            return true;
        } else {
            return false;
        }
    }
    return false;
}


//AJAX call for zip code validity
function getXmlHttpObject() {
    var http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType("text/xml");
        }
    } else {
        if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                }
            }
        }
    }
    if (!http_request) {
        return false;
    }
    return http_request;
}
function checkZipValidity(zip) {
    var xmlHttp = getXmlHttpObject();
    //xmlHttp.open("GET", "http://localhost:7002/LocalSearchProxy/ValidateZip.do?zip=" + zip, false);
    xmlHttp.open("GET", "http://www.edmunds.com/apps/localsearch/ValidateZip.do?zip=" + zip, false);
    xmlHttp.send(null);
    if (xmlHttp.status == 200) {
        return checkZip(xmlHttp.responseXML);
    } else {
        alert("Error " + xmlHttp.status + ": " + xmlHttp.statusText);
    }
}
function checkZip(xmlDoc) {
    var zip = xmlDoc.getElementsByTagName("zip");
    if (zip.length == 0) {
        alert("Please enter valid city and state or ZIP code.\neg: santa monica, ca or 90404");
        return false;
    }
    return true;
}

// validating city
function checkCityValidity(city, state) {
    var cityWithoutSpaces = city.replace(/\s+/g, "");
    var stateWithoutSpaces = state.replace(/\s+/g, "");
    //alert("checkCityValidity -- called:" + cityWithoutSpaces + ":" + stateWithoutSpaces);
    var xmlHttp = getXmlHttpObject();
    xmlHttp.open("GET", "http://www.edmunds.com/apps/localsearch/ValidateCity.do?city=" + cityWithoutSpaces + "&state=" + stateWithoutSpaces, false);
    //xmlHttp.open("GET", "http://localhost:7002/LocalSearchProxy/ValidateCity.do?city=" + cityWithoutSpaces + "&state=" + stateWithoutSpaces, false);
    xmlHttp.send(null);
    if (xmlHttp.status == 200) {
        return checkCity(xmlHttp.responseXML);
    } else {
        alert("Error " + xmlHttp.status + ": " + xmlHttp.statusText);
    }
}
function checkCity(xmlDoc) {
    var city = xmlDoc.getElementsByTagName("city");
    if (city.length == 0) {
        alert("Please enter valid city and state or ZIP code.\neg: santa monica, ca or 90404");
        return false;
    }
    return true;
}
// end functions -- validating city


/*********************************************************************/
// Javascript functions for LocalServiceWidget Component
/*********************************************************************/

/*********************************************************************/
// Javascript functions for LocalServiceDirection Component
/*********************************************************************/
function populateFromField(json) {
  // initailizing the select dropdown
  for(var i=0; i<document.localServiceDirectionForm.daddr.options.length; i++) {
    document.localServiceDirectionForm.daddr.options[i] = null;
  }
  
  var locations = json.location;
  if (locations != null) {
    for (var i = 0; i<locations.length; i++) {
      var location = locations[i];
      var value = location.address.street + " " + location.address.city + ", " + location.address.state + " " + location.address.zip;
      var text = (i+1) + "- " + location.name;
      document.localServiceDirectionForm.daddr.options[i] = new Option(text, value);
    }
  }
}
/*********************************************************************/
// End Javascript functions for LocalServiceDirection Component
/*********************************************************************/

/*********************************************************************/
// Javascript functions for LocationListing Tab View Component
/*********************************************************************/

function populateListingTab(jsonListing) {
    //alert(jsonListing["@svcType"]);
    var svc_type = jsonListing["@svcType"];
    if (svc_type == 'dealerships') {
        populateTab(0, jsonListing);
        updateMoreLocationsLink();
    } else if (svc_type == 'repairshops') {
        populateTab(1, jsonListing);
        updateMoreLocationsLink();
    }
}

function populateTab(tab, jsonListing) {
  //alert("populateTab called");
  if (myTabs == undefined) {
    myTabs = new YAHOO.widget.TabView("locallisting-tabview");
  }
  
  var tabdiv = document.getElementById("locallisting-tabview-tab"+tab);
  
  var childNodes = tabdiv.childNodes;  
  while (childNodes.length > 0) {
        var child = childNodes[0];        
        tabdiv.removeChild(child);
  }
  
  sortListings();
  
  var tabol = createChildElement(tabdiv,"ol","");
  addAttribute(tabol,"class","dealerOverviewContainer noPaddingTop");
  var locs = jsonListing.location;
  if (locs != null) { 
    for (var i=0; i < jsonListing.location.length; i++) {
        var currentLocation = jsonListing.location[i];

        var tabli = createChildElement(tabol,"li","");
        var tabdl = createChildElement(tabli,"dl","");
        addAttribute(tabdl,"class","dealerOverview");
        var tabdt = createChildElement(tabdl,"dt","");

        var tablink = createChildElement(tabdt,"a","");
          if(gSvcType !== undefined) {
            if(gSvcType == 'repairshops') {
                addAttribute(tablink,"href",currentLocation.subPathUrl+"service.1.newOld.html");
            }
            if(gSvcType == 'dealerships') {
                addAttribute(tablink,"href",currentLocation.subPathUrl+"index.html");
            }
        }

        var nameTextNode = document.createTextNode(currentLocation.name);
        tablink.appendChild(nameTextNode);
        
        var tabddAddress = createChildElement(tabdl,"dd","");
        addAttribute(tabddAddress,"class","dealerOverviewAddress");

        var addressTextStreet = currentLocation.address.street;
        var addressTextNodeStreet = document.createTextNode(addressTextStreet);
        tabddAddress.appendChild(addressTextNodeStreet);
        createChildElement(tabddAddress,"br","");

        var addressTextCityEtc = currentLocation.address.city + ", " + currentLocation.address.state + " " + currentLocation.address.zip;
        var addressTextNodeCityEtc = document.createTextNode(addressTextCityEtc);
        tabddAddress.appendChild(addressTextNodeCityEtc);
        createChildElement(tabddAddress,"br","");

        var addressTextPhone = currentLocation.contact.phone;
        var addressTextNodePhone = document.createTextNode(addressTextPhone);
        tabddAddress.appendChild(addressTextNodePhone);
        createChildElement(tabddAddress,"br","");

        var tabddPremierDealer = createChildElement(tabdl, "dd", "");
        /*if((currentLocation.nciGroupId != null) && (currentLocation.nciGroupId != 'undefined') && (currentLocation.nciGroupId.length > 0)) {
            var tabLocalNCIPromo = createChildElement(tabddPremierDealer, "a", "") ;
            addAttribute(tabLocalNCIPromo,"class","NCIPromoLogo-map");
            addAttribute(tabLocalNCIPromo, "href", "javascript:YAHOO.Edmunds.Inventory.jumpToDDP('" + currentLocation.nciGroupId + "', null, '" + currentLocation.address.zip + "');");
        }*/
        
        addAttribute(tabddPremierDealer,"class","premierDealer");
        if (gSvcType == 'dealerships' && currentLocation.isPDP != undefined && currentLocation.isPDP == 'A') {
            var tabPDPLink = createChildElement(tabddPremierDealer, "a", "");
            addAttribute(tabPDPLink, "href", currentLocation.locationURL);
            addAttribute(tabPDPLink, "target", "_blank");
            var tabPDPImage = createChildElement(tabPDPLink, "img", "");
            addAttribute(tabPDPImage,"src","http://a332.g.akamai.net/f/332/936/12h/www.edmunds.com/media/products/localsearch/edmundsPremierDealer.gif");
            addAttribute(tabPDPImage,"alt","Premier Dealer");
            addAttribute(tabPDPImage,"title","Premier Dealer");
        } else {
            tabddPremierDealer.appendChild(document.createTextNode("\u00a0"));
        }

        var tabddSalesReview = createChildElement(tabdl, "dd", "");
        addAttribute(tabddSalesReview,"class","sales-review");
        if (currentLocation.salesRating != undefined) {
            var tabSalesReviewImg = createChildElement(tabddSalesReview, "img", "");
            addAttribute(tabSalesReviewImg,"src",currentLocation.salesRatingImage);
            addAttribute(tabSalesReviewImg,"alt",currentLocation.salesRating + " stars");
            addAttribute(tabSalesReviewImg,"title",currentLocation.salesRating + " stars");
            addAttribute(tabSalesReviewImg,"border","0");

            createChildElement(tabddSalesReview,"br","");
            var tabLinkWriteSaleReview = createChildElement(tabddSalesReview,"a","");
            var reviewLinkText = "";
            var reviewPageName = "";
            if (currentLocation.numSalesReview == 0) {
                if (currentLocation.writeSalesReviewPage != undefined) {
                    reviewPageName = currentLocation.writeSalesReviewPage;
                }
                if (currentLocation.writeSalesReviewText != undefined) {
                    reviewLinkText = currentLocation.writeSalesReviewText;
                }
                addAttribute(tabLinkWriteSaleReview,"href", "javascript:isLoggedIn('" + currentLocation.subPathUrl + reviewPageName + "','');");
            } else if (currentLocation.numSalesReview > 0) {
                reviewLinkText = currentLocation.numSalesReview + " Sales Review";
                if (currentLocation.numSalesReview > 1) {
                    reviewLinkText = reviewLinkText + "s";
                }
                if (currentLocation.salesReviewPage != undefined) {
                    reviewPageName = currentLocation.salesReviewPage;
                }
              addAttribute(tabLinkWriteSaleReview,"href", currentLocation.subPathUrl + reviewPageName);
            }

        var reviewLinkTextNode = document.createTextNode(reviewLinkText);
        tabLinkWriteSaleReview.appendChild(reviewLinkTextNode);
        } else {
          tabddSalesReview.appendChild(document.createTextNode("\u00a0"));
        }

        var tabddServiceReview = createChildElement(tabdl, "dd", "");
        addAttribute(tabddServiceReview,"class","service-review");
        if (currentLocation.serviceRating != undefined) {
            var tabServiceReviewImg = createChildElement(tabddServiceReview, "img", "");
            addAttribute(tabServiceReviewImg,"src",currentLocation.serviceRatingImage);
            addAttribute(tabServiceReviewImg,"alt",currentLocation.serviceRating + " stars");
            addAttribute(tabServiceReviewImg,"title",currentLocation.serviceRating + " stars");
            addAttribute(tabServiceReviewImg,"border","0");

            createChildElement(tabddServiceReview,"br","");
            var tabLinkWriteServiceReview = createChildElement(tabddServiceReview,"a","");
            var reviewLinkText = "";
            var reviewPageName = "";
        if (currentLocation.numServiceReview == 0) {
            if (currentLocation.writeServiceReviewPage != undefined) {
                reviewPageName = currentLocation.writeServiceReviewPage;
            }
            if (currentLocation.writeServiceReviewText != undefined) {
                reviewLinkText = currentLocation.writeServiceReviewText;
            }
            addAttribute(tabLinkWriteServiceReview, "href", "javascript:isLoggedIn('" + currentLocation.subPathUrl + reviewPageName + "','');");
        } else if (currentLocation.numServiceReview > 0) {
            reviewLinkText = currentLocation.numServiceReview + " Service Review";
            if (currentLocation.numServiceReview > 1) {
                reviewLinkText = reviewLinkText + "s";
            }
            if (currentLocation.serviceReviewPage != undefined) {
                reviewPageName = currentLocation.serviceReviewPage;
            }
            addAttribute(tabLinkWriteServiceReview,"href", currentLocation.subPathUrl + reviewPageName);
        }
            var reviewLinkTextNode = document.createTextNode(reviewLinkText);
            tabLinkWriteServiceReview.appendChild(reviewLinkTextNode);
        } else {
            tabddServiceReview.appendChild(document.createTextNode("\u00a0"));
        }
      }
   }
   myTabs.set('activeIndex', tab);
}

function sortTabListings() {
    sortListings();
    var activeIndex = myTabs.get('activeIndex');
    populateTab(activeIndex, gJsonListing);
    clearOverlays();
    createLocationMarkers(gJsonListing);
    populateFromField(gJsonListing);
}

function sortListings() {
    var selectSort = document.sorter.sortSelect;
    var sorterIndex = selectSort.selectedIndex;
    var sortBy = selectSort.options[sorterIndex].value;
    //alert("I am going to sort by " + sortBy);
    var locations = gJsonListing.location;
    if (locations != null) {
        if (sortBy == 'alphabetical') {
            locations.sort(sortByAlpha);
        } else if (sortBy == 'distance') {
            locations.sort(sortByDistance);
        } else if (sortBy == 'highest_sales_rating') {
            locations.sort(sortByHighestSalesRating);
        } else if (sortBy == 'highest_service_rating') {
            locations.sort(sortByHighestServiceRating);
        }
    }
}

function sortByAlpha(a, b) {
    if (a.name == b.name) {
        return 0;
    }
    return (a.name < b.name ? -1 : 1);
}
function sortByDistance(a, b) {
    /*if (a.distance == b.distance) {
        return 0;
    }
    return (a.distance < b.distance ? -1 : 1);
    */
    if (a.distance == b.distance) {
        return sortByAlpha(a, b);
    }

    return (a.distance-b.distance);
}

function sortByHighestSalesRating(a, b) {
    if (a.salesRating == b.salesRating) {
        return 0;
    }
    return (a.salesRating > b.salesRating ? -1 : 1);
}

function sortByHighestServiceRating(a, b) {
    if (a.serviceRating == b.serviceRating) {
        return 0;
    }
    return (a.serviceRating > b.serviceRating ? -1 : 1);
}

//DOM utility methods
function createChildElement(parent, childName, id){
    var newElem = document.createElement(childName);
    //addAttribute(newElem, "id", id);
    parent.appendChild(newElem);
    return newElem;
}

function removeChildElement(parent, childName, id) {
    var delelem = document.getElementById(id);
    if (delelem != null) {
            parent.removeChild(delelem);
    }
}

function addAttribute(element, attrName, attrValue) {
    var newAttrNode = document.createAttribute(attrName);
    newAttrNode.nodeValue= attrValue;
    element.setAttributeNode(newAttrNode);
}

function updateSortOrdersForTab(eventInfo) {
    if (eventInfo.newValue === eventInfo.prevValue) {
        //alert("same");
    	return;
    }
    var activeIdx = myTabs.get('activeIndex');
    //alert(activeIdx);
    var counter = 0;
    var sortListing = document.sorter.sortSelect;
    var curSelIdx = sortListing.selectedIndex;
    sortListing.options.length = 0;
    sortListing.options[counter++] = new Option("Distance","distance");
    if (activeIdx == 0) {
       sortListing.options[counter++] = new Option("Highest Sales Rating","highest_sales_rating");
    }
    sortListing.options[counter++] = new Option("Highest Service Rating","highest_service_rating");
    sortListing.options[counter++] = new Option("Alphabetical","alphabetical");
    var newSelIdx = curSelIdx;
    if (activeIdx == 1) {
        if (curSelIdx == 2) {
            newSelIdx = 1;
        } else if (curSelIdx == 3) {
            newSelIdx = 2;
        }
    } else if (activeIdx == 0) {
        if (curSelIdx == 2) {
            newSelIdx = 3;
        } else if (curSelIdx == 1) {
            newSelIdx = 2;
        }
    }
    sortListing.options[newSelIdx].selected = true;
    sortListing.blur();
}

function updateMoreLocationsLink() {    
    var moreLink = document.getElementById('more_locations_link');
    var linkRef, linkText;
    
    var svc_type = gJsonListing["@svcType"];
    if (svc_type == 'dealerships') {
        linkText = "More Car Dealers";
    } else if (svc_type == 'repairshops') {
        linkText = "More Repair Shops";
    } 
    linkRef = gJsonListing.moreLink;
    
    var moreLinkElem = document.getElementById("more_locations_link");
    moreLinkElem.setAttribute('href',linkRef);
    moreLinkElem.innerHTML = linkText;   
}

/*********************************************************************/
// End Javascript functions for LocationListing Tab View Component
/*********************************************************************/
