﻿/* JavaScript file common to all the web pages */

// Global variable declaration
var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])
var className = '';
var imgAltText;
var currentPageName = unescape(window.location.pathname);
var overlaysKeys =
   {
       parking: "", gyms: "", pubs: "", schools: "", hospitals: "", railwayStation: "", underground: "",
       localShops: "", cinemas: "", libraries: "", wikipedia: "", publicTransport: ""
   };
/* Filter Parameters used to get properties on map dragged */
var BedRooms,MinimumPrice,MaximumPrice,ResidenceType,StreetParkingOption ="0",OutDoorSpaceOption="0",GarageOption="0",SaleOrLeaseOption,
UnderContractOption,PropertyAddedWhen,ReducingPriceOption;

/* Global Variables used for prices and trends 
   PT i.e Price and Trends
*/

var PTStartMonth, PTEndMonth, PTStartYear,PTEndYear,PTPropertyType,PTMinPrice,PTMaxPrice;
var TrendsDataOverlayType = '', IsTrendsHeatMapLinksClicked = false;
var start_loc,end_loc,via_loc;

var Start_Location,End_Location,Via_Location, ShowDistance;
var Shortest,Walking, isErrorPage= false;
var isCheckboxRentBuyClicked=false;

var TxtLocalSearchCategory = undefined;
var AmenitiesDefaultSearhText = "E.g. dry cleaners, coffee shops";
var isBusinessDirectorySearch = false;

/* Function Used to fix the Alpha transparency for a png image */
function fixPNG(myImage) {
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) {
        var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
        var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
        var imgTitle = (myImage.title) ?
                                             "title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
        var imgStyle = "display:inline-block;" + myImage.style.cssText
        var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width
                  + "px; height:" + myImage.height
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
        myImage.outerHTML = strNewHTML
    }
}

/* Function used to fix the alpha transparency for all the png images in the document  */
function fixup() {
    for (var i = 0; i < document.images.length; i++) {
        var img = document.images[i]
        var imgName = img.src.toUpperCase()
        if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
	         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML
            i = i - 1
        }
    }
}

/* Function used for fixing the map png images alpha transparency */
function fixMapPngImages() {
    if (navigator.appName == "Microsoft Internet Explorer") {
        var mapViewer = document.getElementById("dvMapViewer");
        var mapImages = mapViewer.getElementsByTagName('img');
        for (var i = 0; i < mapImages.length; i++) {
            var img = mapImages[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
	         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                img.outerHTML = strNewHTML
                i = i - 1
            }
        }
    }

}



/* Function used for Reseting the Amenities and Local information options based on querystring */
function ResetAmenitiesOptions() {
    var qAmenities = getQStringValue("poi");
    if (qAmenities) {
        qAmenities = qAmenities.replace(/%7c/g, "|");
        qAmenities = qAmenities.replace("#", "");
        var arrayAmenities = qAmenities.split('|')
        if (arrayAmenities.length > 0) {
            for (var i = 0; i < arrayAmenities.length; i++) {
                var el = document.getElementById('show_' + arrayAmenities[i]);
                if (el) {
                    el.checked = true;
                }
            }
        }
    }
    var queryStringBusinessSearch = getQStringValue("query");
    if (IsNullOrEmpty(queryStringBusinessSearch)) {
       if(!TxtLocalSearchCategory) {
            TxtLocalSearchCategory = document.getElementById("ctl00_LeftNavigationControl1_txtSearchLocal");
        }
       if(queryStringBusinessSearch.length > 30) {
           queryStringBusinessSearch = queryStringBusinessSearch.substring(0,30);
       } 
       TxtLocalSearchCategory.value = unescape(queryStringBusinessSearch);
    }    
    return false;
}
/* Function used for Reseting the Amenities and Local information options based on querystring */
function ResetSchoolOptions() {
    var qAmenities = getQStringValue("schools");
    if (qAmenities) {
        if (qAmenities == "all"){ 
            qAmenities = qAmenities + '|'+ GetAllSchoolsHashQStringValue();        
        }
        qAmenities = qAmenities.replace(/%7c/g, "|");
        qAmenities = qAmenities.replace("#", "");
        var arrayAmenities = qAmenities.split('|')
        if (arrayAmenities.length > 0) {
            for (var i = 0; i < arrayAmenities.length; i++) {
                var el = document.getElementById('show_' + arrayAmenities[i]);
                if (el) {
                    el.checked = true;
                }
            }
        }
    }
    return false;
}
/* Function used for Reseting the Amenities and Local information options based on querystring */
function ResetLocalInformationOptions() {
    var qAmenities = getQStringValue("localinfo");
    var qOverlays = getQStringValue("overlays");
    if (qAmenities) {
        qAmenities = qAmenities.replace(/%7c/g, "|");
        qAmenities = qAmenities.replace("#", "");
        var el = document.getElementById('show_' + qAmenities);
        if (el) {
            el.checked = true;
        }
    }
      if (qOverlays) {        
        var el = document.getElementById('show_' + qOverlays);
        if (el) {
            ShowHideCustomOverlayLegend(qOverlays.toLowerCase());
            el.checked = true;
        }
    }
    return false;
}
/* Function used for retrieving the querystring values based on the key */
function getQStringValue(field) {
    //unescape is used to decode the url %20 will be converted with space
    var qString;
    if(field == "overlays" || field == "schools" || field == "poi" || field == "localinfo" || field == "prpty" || field == "ptrends" ||field == "heatMap" || field == "map"){
        qString = unescape(window.location.hash.substring(1));
    }else{
        qString = unescape(window.location.search.substring(1));
    }
    var arrQStrings = qString.split("&");
    for (i = 0; i < arrQStrings.length; i++) {
        var arrFields = arrQStrings[i].split("=");
        if (arrFields[0] == field) {
            return arrFields[1];
        }
    }
}

/* Replace the queryString variables */
function replaceQueryString(url, param, value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
}

/* Function used to open the help link page */
function OpenHelpPage() {
    window.open("http://money.uk.msn.com/MSN-Local/help.aspx");
}


/* Function used to open the help link page for crime statistics*/
function OpenCrimeStatisticsHelpPage() {
    window.open("http://money.uk.msn.com/MSN-Local/help.aspx#C");
}

/* Function used to open the help link page  for flood risk information */
function OpenFloodRiskInformationHelpPage() {
    window.open("http://money.uk.msn.com/MSN-Local/help.aspx#F");
}

/* Function used to open the help link page  for Disclaimer information */
function OpenDisclaimerInformationHelpPage() {
    window.open("http://money.uk.msn.com/MSN-Local/help.aspx#D");
}

/* Function used to open the help link page  for Properties for sale or rent */
function OpenPreferencesHelpPage() {
    window.open("http://money.uk.msn.com/MSN-Local/help.aspx#M");
}

/* Function used to open the help link page  for Properties for sale or rent */
function OpenPriceTrendHelpPage() {
    window.open("http://money.uk.msn.com/MSN-Local/help.aspx#P");
}

function showHelpText(divId,altTextDiv)
{
    imgAltText = document.getElementById(altTextDiv).alt;
    document.getElementById(altTextDiv).alt='';
    document.getElementById(divId).style.display = "";
}

function hideHelpText(divId,altTextDiv)
{
    document.getElementById(divId).style.display = "none";
    document.getElementById(altTextDiv).alt = imgAltText;
}
/* Function used to open the property finder site */
function OpenPropertyFinderWebSite() {
    window.open("http://www.zoopla.co.uk/");
}
function OpenShootHillWebSite() {
    window.open("http://www.shoothill.com/");
}


/////////////////////// Left Nav Control //////////////
//////////////////////////////////////////////////////



// function used for disabling the Property under offer on click 
// of buy or rent radio buttons used in the HomePageProperty search control
// and property search control

function disableListItems(checkBoxListId, chkArray, disable) {
    // Get the checkboxlist object.
    objCtrl = checkBoxListId.id;

    // Does the checkboxlist not exist?
    if (objCtrl == null)
        return;

    var i = 0;
    objItem = document.getElementById(objCtrl + '_' + chkArray); // Object of the Price under offer ListItem

    // Disable/Enable the checkbox.
    objItem.disabled = disable;
    if (disable ) {
        objItem.checked = false;
    
    }

    // Should the checkbox be disabled?
    //objItem.checked = disable;
}

////This functionality handle the leftnavigation control behaviour///////////////////
////////////////////////////////////////////////////////////////////////////////////

/* Function used for clicking on left pane div */
function HandleDivClick(parentDivID, displayDivID, chkBoxId) {
        var displayDiv = document.getElementById(displayDivID);
        var focusOnDiv = document.getElementById(parentDivID);
        var chkExpanded = document.getElementById(chkBoxId);

        var PropertyFilterDiv = document.getElementById('propertySearchDiv');
        var AmentiesDiv = document.getElementById('amentiesDiv');
        var SchoolDiv = document.getElementById('schoolDiv');
        var LocalInformationDiv = document.getElementById('localInformationDiv');
        var DirectionsDiv = document.getElementById('directionsDiv');
        var priceTrendDisplayDiv = document.getElementById('priceTrendDisplayDiv');
        
        //reset the divs
        PropertyFilterDiv.style.display = 'none';
        AmentiesDiv.style.display = 'none';
        SchoolDiv.style.display = 'none';
        LocalInformationDiv.style.display = 'none';
        DirectionsDiv.style.display = 'none';
        priceTrendDisplayDiv.style.display = 'none';

        //display the current div
        displayDiv.style.display = '';

        //maintain the focus on current div        
        focusOnDiv.focus();

        //property filter
        if (IsPropertySearchControlChecked()) {
            document.getElementById('chkBuyORRent').checked = true;
        }
        else {
            document.getElementById('chkBuyORRent').checked = false;
        }
        //check prices and trends
        if(isPricesAndTrendsChecked()){ 
        document.getElementById('chkPriceAndTrends').checked = true;
        }
        else {
            document.getElementById('chkPriceAndTrends').checked = false;
        }

        //amenties information     
        var localInfo = document.getElementById("localInfo");
        if (checkAmemtiesValues(localInfo)) {
            document.getElementById('chkAmenties').checked = true;
        }
        else {
            document.getElementById('chkAmenties').checked = false;
        }

        //school information
        var schoolInfo = document.getElementById("schoolsLocalInfo");
        if (checkAmemtiesValues(schoolInfo)) {
            document.getElementById('chkSchool').checked = true;
        }
        else {
            document.getElementById('chkSchool').checked = false;
        }

        //Wikipedia informations  
        var wikipediaInfo = document.getElementById("wikipediaLocalInfo");
          var overlayInfo = document.getElementById("overlaysDiv");
        if (checkAmemtiesValues(wikipediaInfo) || checkAmemtiesValues(overlayInfo)) {
            document.getElementById("chkLocalInformation").checked = true;
        }
       
        else {
            document.getElementById('chkLocalInformation').checked = false;
        }
        
       if(focusOnDiv.id ==  "DirectionsParentDiv"){
            document.getElementById('startLocation').focus();
       }
       if(isRouteVisible())
       {
            document.getElementById('chkDirections').checked = true;
            //document.getElementById('startLocation').focus();
       }
       else
       {
            document.getElementById('chkDirections').checked = false;
       }
        
        if(!TxtLocalSearchCategory) 
        {
            TxtLocalSearchCategory = document.getElementById("ctl00_LeftNavigationControl1_txtSearchLocal");
        }
        if(TxtLocalSearchCategory.value != "" && TxtLocalSearchCategory.value != AmenitiesDefaultSearhText) {
         document.getElementById('chkAmenties').checked = true;
        }
        //set expanded checkbox true
        chkExpanded.checked = true;
        

}

function isRouteVisible()
{
    if(currentPageName.toLowerCase().indexOf("directions")>-1 && IsMapVisible()){
        if(route && route.polyLine){
            if(route.polyLine.length > 0){
                return true;
            }
        }
    }
    return false;
}
/*prices and trends information*/

function isPricesAndTrendsChecked()
{ 
    if (currentPageName.toLowerCase().indexOf("map")>-1 || currentPageName.toLowerCase().indexOf("directions")>-1 || currentPageName.toLowerCase().indexOf("priceandtrendproperties")>-1) 
    {
       if (document.getElementById("dvMapViewer")) 
       {
         if(trendsPropertyMarkers)
         {
           if(trendsPropertyMarkers.length>0 || currentHeatMap != null)
           {
              return true;
           }
         }                        
       }  
    }
    var drpPropertyType = readTelerikControlValue("drpPricesAndTrendsFor", "ctrlPrefixForPriceAndTrends");
    if (drpPropertyType.get_value() != "any") {
        return true;
    }
    
    var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPriceAndTrends");
    var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPriceAndTrends");
    if (drpMaxBudget.get_value() != "nm"){
          return true;
        }
    if (drpMinBudget.get_value() != "0"){
        return true;
    }
    var drpToYear = readTelerikControlValue("drpToYear", "ctrlPrefixForPriceAndTrends");
    var drpFromYear = readTelerikControlValue("drpFromYear", "ctrlPrefixForPriceAndTrends");
    
    var drpToMonth = readTelerikControlValue("drpToMonth", "ctrlPrefixForPriceAndTrends");
    var drpFromMonth = readTelerikControlValue("drpFromMonth", "ctrlPrefixForPriceAndTrends");
    
    var d = new Date();   
    if(drpToYear.get_value() !=d.getFullYear()) {
     return true ;
    }

   if(drpFromYear.get_value() !=d.getFullYear()-2){
      return true;    
    }
     if(drpToMonth.get_value() !=d.getMonth()+1){
     return true ;
    }
     if(drpFromMonth.get_value() !=d.getMonth()+1) {
     return true ;
    }
    
  return false;

}

/* Get the check box information for checked.*/
function checkAmemtiesValues(localInformation) {

    var isChecked = false;
    //var localInfo=document.getElementById(localInformation);
    if(localInformation.id != "overlaysDiv")
    {
        var amenities = localInformation.getElementsByTagName('input');
        for (var j = 0; j < amenities.length; j++) {
            if (amenities[j].checked == true) 
            {
                isChecked = true;
                break;
            }
        }
    }
    else
    {
        var overlays = localInformation.getElementsByTagName('input');
        for (var j = 0; j < overlays.length; j++) {
            if (overlays[j].checked == true) 
            {
                if(overlays[j].id != "show_none")
                {
                    isChecked = true;
                }               
                break;
            }
        }
        
        
    } 
   
    return isChecked;
}

/*Reset/uncheck the amenties information. */
function UncheckTheControlsValues(controlInfromation) {
    //var controlInfromation=document.getElementById(controlID);   
    
    if(controlInfromation.id != "overlaysDiv")
    {
         var amenities = controlInfromation.getElementsByTagName('input');
        for (var j = 0; j < amenities.length; j++) {
            amenities[j].checked = false;
        }
    }
    else
    {
        document.getElementById("show_none").checked = true;
        showCrimeMapKey(false);
        ShowConstituencyPartyColorDiv(false);
    }   
}

/* Function used to reset the controls values in the navigation bars */
function ResetInnverValues(chkBoxID, chkvalue, parentDivID) {
//    setTimeout(function() { 
        var chkObject = document.getElementById(chkBoxID);
        //var currentPageName = unescape(window.location.pathname);
        var focusOnDiv = document.getElementById(parentDivID);
        var PropertyFilterDiv = document.getElementById('propertySearchDiv');
        var AmentiesDiv = document.getElementById('amentiesDiv');
        var SchoolDiv = document.getElementById('schoolDiv');
        var LocalInformationDiv = document.getElementById('localInformationDiv');
        var DirectionsDiv = document.getElementById('directionsDiv');
        var priceTrendDisplayDiv = document.getElementById('priceTrendDisplayDiv');
        
        switch (chkvalue) {
            case "chkBuyORRent": //reset the property property filter control
                {
                    isCheckboxRentBuyClicked=true;
                    if (chkObject.checked == false) 
                    {
                        if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                            //showDirectionsUserMessage("amenities");
                            chkObject.checked = true;
                        }else{
                            chkObject.checked = false;
                            UncheckThePropertyFilter();
                            if (currentPageName.indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 || currentPageName.indexOf("directions")>-1 ) 
                            {
                              if (document.getElementById("dvMapViewer")) 
                              {
                               //only remove the properties if map is visible
                               if(IsMapVisible())
                               {
                                  ClearPropertiesOverlay();
                                  showShootHillLogo();
                               } 
                              } 
                            }
                        }
                    }
                    if (chkObject.checked) {
                        AmentiesDiv.style.display = 'none';
                        SchoolDiv.style.display = 'none';
                        LocalInformationDiv.style.display = 'none';
                        DirectionsDiv.style.display = 'none';
                        priceTrendDisplayDiv.style.display = 'none';
                        PropertyFilterDiv.style.display = '';
                        checkInnerControlsValue();
                        chkObject.checked = true;
                        focusOnDiv.focus();
                    }
                    break;
                }

            case "chkAmenties": //reset the amenties
                {

                    if (chkObject.checked == false) {
                        if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                            showDirectionsUserMessage("amenities");
                            chkObject.checked = true;
                        }else {
                            var localInfo = document.getElementById("localInfo");
                            chkObject.checked = false;
                            UncheckTheControlsValues(localInfo);
                            UpdateQStringHashVariable(amenitiesTag,'',false);
                            if(!TxtLocalSearchCategory) {
                                 TxtLocalSearchCategory = document.getElementById("ctl00_LeftNavigationControl1_txtSearchLocal");
                            }
                            TxtLocalSearchCategory.value = AmenitiesDefaultSearhText;
                            document.getElementById("amenitiesusermsg").style.display = 'none';
                            if (currentPageName.indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 || currentPageName.indexOf("directions")>-1 ) {
                            if (document.getElementById("dvMapViewer")) 
                             {
                               //only remove the properties if map is visible
                               if(IsMapVisible())  {
                                 clearVEOverlays();
                                 SetPagerLinksVisibility(false);
                                 removeUncheckedOverlays();
                                 removeUncheckedVEOverlays();
                               } 
                             } 
                            }
                        }
                    }
                    if (chkObject.checked) {
                        SchoolDiv.style.display = 'none';
                        LocalInformationDiv.style.display = 'none';
                        PropertyFilterDiv.style.display = 'none';
                        DirectionsDiv.style.display = 'none';
                        priceTrendDisplayDiv.style.display = 'none';
                        AmentiesDiv.style.display = '';
                        checkInnerControlsValue();
                        chkObject.checked = true;
                        focusOnDiv.focus();
                    }

                    break;
                }

            case "chkSchool": //reset the school 
                {
                    if (chkObject.checked == false) {
                      if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                            showDirectionsUserMessage("schools");
                            chkObject.checked = true;
                        }else {
                            var schoolInfo = document.getElementById("schoolsLocalInfo");
                            chkObject.checked = false;
                            UncheckTheControlsValues(schoolInfo);
                            UpdateQStringHashVariable(schoolTag,'',false);
                            document.getElementById("schoolsusermsg").style.display = 'none';
                            if (currentPageName.indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 || currentPageName.indexOf("directions")>-1 ) {
                            
                               if (document.getElementById("dvMapViewer")) 
                               {
                                 //only remove the properties if map is visible
                                if(IsMapVisible())
                                {
                                 //function used to remove the markers from the map for schools
                                 cleanSchoolOverlays();                            
                                } 
                               }  
                            }
                         }
                    }
                    if (chkObject.checked) {
                        SchoolDiv.style.display = '';
                        LocalInformationDiv.style.display = 'none';
                        PropertyFilterDiv.style.display = 'none';
                        AmentiesDiv.style.display = 'none';
                        priceTrendDisplayDiv.style.display = 'none';
                        DirectionsDiv.style.display = 'none';
                        checkInnerControlsValue();
                        chkObject.checked = true;
                        focusOnDiv.focus();

                    }
                    break;
                }

            case "chkLocalInformation": //reset the local information
                {
                    
                    if (chkObject.checked == false) {
                        if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                            showDirectionsUserMessage("localinfo");
                            chkObject.checked = true;
                        } else {
                            var wikiPediaInfo = document.getElementById("wikipediaLocalInfo");                        
                            chkObject.checked = false;
                            UncheckTheControlsValues(wikiPediaInfo);
                            var overlayInfo = document.getElementById("overlaysDiv");
                            UncheckTheControlsValues(overlayInfo);
                            UpdateQStringHashVariable(overlaysTag,'',false);
                            UpdateQStringHashVariable(localinfoTag,'',false);
                            document.getElementById("localinfousermsg").style.display = 'none';
                            if (currentPageName.indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 || currentPageName.indexOf("directions")>-1 ) {
                            if (document.getElementById("dvMapViewer")) 
                               {
                                 //only remove the properties if map is visible
                                 if(IsMapVisible())
                                 {
                                   clearLocalInformationOverlays("wikipedia");
                                   displayConstituencyOverlay("none");
                                   if (currentPageName.indexOf("map")>-1){ 
                                     showShootHillLogo();
                                   }
                                 }  
                               } 
                            }
                        }
                    }
                    if (chkObject.checked) {
                        PropertyFilterDiv.style.display = 'none';
                        AmentiesDiv.style.display = 'none';
                        SchoolDiv.style.display = 'none';
                        priceTrendDisplayDiv.style.display = 'none';
                        DirectionsDiv.style.display = 'none';
                        LocalInformationDiv.style.display = '';
                        checkInnerControlsValue();
                        chkObject.checked = true;
                        focusOnDiv.focus();
                    }
                    break;
                }
             case "chkDirections": //reset the directions
                {
                    if (chkObject.checked == false){
                        if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                            chkObject.checked = true;
                        }else{
                            chkObject.checked = false;
                            clearDirectionsOptions();
                             if (currentPageName.indexOf("directions")>-1){
                                if(IsMapVisible())
                                {
                                    clearRoutemap();
                                }
                             }
                         }
                    }
                    if (chkObject.checked) {
                        PropertyFilterDiv.style.display = 'none';
                        AmentiesDiv.style.display = 'none';
                        SchoolDiv.style.display = 'none';
                        LocalInformationDiv.style.display = 'none';
                        priceTrendDisplayDiv.style.display = 'none';
                        DirectionsDiv.style.display = '';
                        checkInnerControlsValue();
                        chkObject.checked = true;
                        //focusOnDiv.focus();
                        document.getElementById('startLocation').focus();
                    }
                    break;
                } 
                
                case "chkPriceAndTrends": //reset the price trends information
                {
                    
                     if (chkObject.checked == false) 
                    {
                        if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                            chkObject.checked = true;
                        }else{
                            chkObject.checked = false;
                            ResetPricesAndTrendsValues();
                             if (currentPageName.indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 || currentPageName.indexOf("directions")>-1 ) {
                                clearTrendsPropertiesOverlay();
                                ClearAllTrendsDataOverlays();
                             }
                         }
                    }
                    if (chkObject.checked) {
                        AmentiesDiv.style.display = 'none';
                        SchoolDiv.style.display = 'none';
                        LocalInformationDiv.style.display = 'none';
                        DirectionsDiv.style.display = 'none';
                        PropertyFilterDiv.style.display = 'none';
                        priceTrendDisplayDiv.style.display = '';
                        checkInnerControlsValue();
                        chkObject.checked = true;
                        focusOnDiv.focus();
                    }
                    break;
                }
                
                  
        }

//    }, 50); //end of delay interval

}

/* Reset the inner Controls Values */
function checkInnerControlsValue() {    //property filter
    if (IsPropertySearchControlChecked()) {
        document.getElementById('chkBuyORRent').checked = true;
    }
    else {
        document.getElementById('chkBuyORRent').checked = false;
    }
    
    //check the prices and trends 
    if(isPricesAndTrendsChecked()){
        document.getElementById('chkPriceAndTrends').checked = true;
    }
    else {
        document.getElementById('chkPriceAndTrends').checked = false;
    }
   

    //amenties information     
    var localInfo = document.getElementById("localInfo");
    if (checkAmemtiesValues(localInfo)) {
        document.getElementById('chkAmenties').checked = true;
    }
    else {
        document.getElementById('chkAmenties').checked = false;
    }

    //school information
    var schoolInfo = document.getElementById("schoolsLocalInfo");
    if (checkAmemtiesValues(schoolInfo)) {
        document.getElementById('chkSchool').checked = true;
    }
    else {
        document.getElementById('chkSchool').checked = false;
    }

    //Wikipedia informations  
    var wikipediaInfo = document.getElementById("wikipediaLocalInfo");      
    var overlayInfo = document.getElementById("overlaysDiv");       
    if (checkAmemtiesValues(wikipediaInfo) || checkAmemtiesValues(overlayInfo)) {
        document.getElementById('chkLocalInformation').checked = true;
    }
    else {
        document.getElementById('chkLocalInformation').checked = false;
    }
    document.getElementById('chkDirections').checked = false;
}

/* This function reset the leftnavigation control at first time load. */
function RestNavigationTabCheckBoxes() { 
    //expand the div according to querystring variable
    var queryString = window.location.search;
    if (queryString.indexOf("search") > -1) 
    {
        var amentiesValue = getQStringValue("search")
        var PropertyFilterDiv = document.getElementById('propertySearchDiv');
        var AmentiesDiv = document.getElementById('amentiesDiv');
        var SchoolDiv = document.getElementById('schoolDiv');
        var LocalInformationDiv = document.getElementById('localInformationDiv');
        var DirectionsDiv = document.getElementById("directionsDiv");

        //reset the divs
        PropertyFilterDiv.style.display = 'none';
        AmentiesDiv.style.display = 'none';
        SchoolDiv.style.display = 'none';
        LocalInformationDiv.style.display = 'none';
        DirectionsDiv.style.display = 'none';
        document.getElementById('priceTrendDisplayDiv').style.display = 'none';

        switch(amentiesValue)
        {
            case "1" : // for amenities search
            {
                 AmentiesDiv.style.display = '';
                 document.getElementById('chkAmenties').checked = true;
                 break;
            }
            case "2" : // for school search
            {
                 SchoolDiv.style.display = '';
                 document.getElementById('chkSchool').checked = true;
                 break;
            }
            case "3" : //for local information search
            {
                LocalInformationDiv.style.display = '';
                document.getElementById('chkLocalInformation').checked = true;
                var qBuyOrRent = getQStringValue("rntorbuy");
                if(IsNullOrEmpty(qBuyOrRent)) {
                   document.getElementById('chkBuyORRent').checked = true;
                }
                break;
            }
            case "6" : //// search comes from property details page
            {
              var schoolId = getQStringValue("schoolid");
              if (schoolId && schoolId != "")
              {
                 SchoolDiv.style.display = '';
                 document.getElementById('chkSchool').checked = true;
                 break;
              }
              else
              {
                  AmentiesDiv.style.display = '';
                  document.getElementById('chkAmenties').checked = true;
                  break;
              }
            }
            default:
            {
              AmentiesDiv.style.display = '';
              document.getElementById('chkAmenties').checked = true;
            }
        }

    }//end of map search types
    
    else if(currentPageName.toLowerCase().indexOf("priceandtrend")>-1 || currentPageName.toLowerCase().indexOf("priceandtrends.aspx")>-1 || currentPageName.toLowerCase().indexOf("priceandtrendproperties.aspx")>-1)
    {
        document.getElementById('priceTrendDisplayDiv').style.display = '';
        //document.getElementById('propertySearchDiv').style.display = 'none';
        document.getElementById('chkPriceAndTrends').checked = true;
       
    }
     else if(currentPageName.indexOf("directions")>-1 || currentPageName.toLowerCase().indexOf("routeplanner")>-1)
    {
        document.getElementById('directionsDiv').style.display = '';
        //document.getElementById('propertySearchDiv').style.display = 'none';
        document.getElementById('chkDirections').checked = true;
        document.getElementById('startLocation').focus();
    }
    else {
        document.getElementById('propertySearchDiv').style.display = '';
        document.getElementById('chkBuyORRent').checked = true;
    }
    isPropertyVisible =  getQueryStringValue("prpty");
    //property search information
    if (maintainTheStateOfPropertySearchControl() || (isPropertyVisible == "1")) {
        document.getElementById('chkBuyORRent').checked = true;
    }

    //amenties information           
    var localInfoAmenities = document.getElementById("localInfo");
    if (checkAmemtiesValues(localInfoAmenities)) {
        document.getElementById("chkAmenties").checked = true;
    }

    //school information
    var schoolInfo = document.getElementById("schoolsLocalInfo");
    if (checkAmemtiesValues(schoolInfo)) {
        document.getElementById("chkSchool").checked = true;
    }

    //wikipedia
    var localInfoWikipedia = document.getElementById("wikipediaLocalInfo");
    var overlayInfo = document.getElementById("overlaysDiv");
    if (checkAmemtiesValues(localInfoWikipedia) || checkAmemtiesValues(overlayInfo)) {
        document.getElementById("chkLocalInformation").checked = true;
    }

    var queryStringBusinessSearch =  getQStringValue("query");
    if (IsNullOrEmpty(queryStringBusinessSearch))
    {
      document.getElementById('chkAmenties').checked = true;
    }
    isPTrendsVisible = getQStringValue("ptrends");
    //maintain the state of prices and trends   
    if((queryString.indexOf("IsPrTrnds") > -1 && getQStringValue("IsPrTrnds")==1) || isPTrendsVisible == "1" || getQStringValue('heatMap') != null)
    {   
    document.getElementById('chkPriceAndTrends').checked=true ;
    }
}
//This function is used to 
function validatePriceAndTrend()
{
   
    var dvPriceAndTrendsErrorDetails = document.getElementById("dvPriceAndTrendsErrorDetails");
    var divPriceAndTrendErrorMsg = document.getElementById("divPriceAndTrendErrorMsg");  

    var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPriceAndTrends");
    var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPriceAndTrends");
    
    var drpToYear = readTelerikControlValue("drpToYear", "ctrlPrefixForPriceAndTrends");
    var drpFromYear = readTelerikControlValue("drpFromYear", "ctrlPrefixForPriceAndTrends");
    
    var drpToMonth = readTelerikControlValue("drpToMonth", "ctrlPrefixForPriceAndTrends");
    var drpFromMonth = readTelerikControlValue("drpFromMonth", "ctrlPrefixForPriceAndTrends");
   
    //if search text is not entered it will return the value false
    if (parseInt(drpMaxBudget.get_value()) < parseInt(drpMinBudget.get_value())) {
        dvPriceAndTrendsErrorDetails.style.display = '';                
        divPriceAndTrendErrorMsg.innerHTML = "Maximum budget should be greater than minimum budget";
        return false;
    }
    
    
    if(new Date(drpToYear.get_value() ,drpToMonth.get_value() ,1)<=new Date(drpFromYear.get_value() ,drpFromMonth.get_value(),1))
    {
       dvPriceAndTrendsErrorDetails.style.display = '';                
        divPriceAndTrendErrorMsg.innerHTML = "Date range is not valid. From date range should be before to date.";
        return false;
    }
    
    else {
        dvPriceAndTrendsErrorDetails.style.display = 'none';
        dvPriceAndTrendsErrorDetails.style.visibility = 'hidden';
        divPriceAndTrendErrorMsg.style.display = 'none';
        divPriceAndTrendErrorMsg.style.visibility = 'hidden';
        return true;
    }
  
}

function FindQueryStringOfPriceAndTrends()
{
  var queryStringParameter = ""; 
  var isPriceTrendsChecked=0 ;
  var drpPricesAndTrendsFor = readTelerikControlValue("drpPricesAndTrendsFor", "ctrlPrefixForPriceAndTrends");
  if(drpPricesAndTrendsFor.get_value()!='any')
  {
     queryStringParameter=queryStringParameter+"&PrcTrndFor="+drpPricesAndTrendsFor.get_value();
     PTPropertyType = drpPricesAndTrendsFor.get_value();
     isPriceTrendsChecked=1;
  }  else  {
    PTPropertyType = null;
  }
  var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPriceAndTrends");
  if(drpMinBudget.get_value()!='0')
  {
    queryStringParameter=queryStringParameter+"&PrcTrdMinPrc="+drpMinBudget.get_value();
    PTMinPrice = drpMinBudget.get_value();
    isPriceTrendsChecked=1;
  } else {
   PTMinPrice = null;
  }
  
 
  var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPriceAndTrends"); 
  if(drpMaxBudget.get_value()!='nm')
  {
    queryStringParameter=queryStringParameter+"&PrcTrdMaxPrc="+drpMaxBudget.get_value();
    PTMaxPrice = +drpMaxBudget.get_value();
    isPriceTrendsChecked=1;
  } else {
   PTMaxPrice = null;
  }
  
   var toYear = readTelerikControlValue("drpToYear", "ctrlPrefixForPriceAndTrends");
   var fromYear = readTelerikControlValue("drpFromYear", "ctrlPrefixForPriceAndTrends");
    
   var toMonth = readTelerikControlValue("drpToMonth", "ctrlPrefixForPriceAndTrends");
   var fromMonth = readTelerikControlValue("drpFromMonth", "ctrlPrefixForPriceAndTrends");
    
   var d = new Date();  
     
    if(fromMonth.get_value() !=d.getMonth()+1) {
       queryStringParameter=queryStringParameter+"&frmMonth="+fromMonth.get_value();
       PTStartMonth = fromMonth.get_value();
       isPriceTrendsChecked=1;
    } 
    
    if(fromYear.get_value() !=d.getFullYear()-2){
      queryStringParameter=queryStringParameter+"&frmYear="+fromYear.get_value();
    PTStartYear = fromYear.get_value();
    isPriceTrendsChecked=1;
    }
    
    if(toMonth.get_value() !=d.getMonth()+1){
      queryStringParameter=queryStringParameter+"&toMonth="+toMonth.get_value();
    PTEndMonth = toMonth.get_value();
    isPriceTrendsChecked=1;
    }
    
    if(toYear.get_value() !=d.getFullYear()) {
      queryStringParameter=queryStringParameter+"&toYear="+toYear.get_value(); 
    PTEndYear = +toYear.get_value();
    isPriceTrendsChecked=1;
    }

 
    
 // for adding the heat map overlays 
 if(IsNullOrEmpty(TrendsDataOverlayType)) {
   switch(TrendsDataOverlayType) {
         case 'AveragePrices':
            //queryStringParameter=queryStringParameter+"&heatMap=AveragePrices";
            UpdateQStringHashVariable("heatMap","ap",true);
            break;
         case 'RentalYeild':
            //queryStringParameter=queryStringParameter+"&heatMap=RentalYeild";
            UpdateQStringHashVariable("heatMap","ry",true);
            break;
         case 'RisersAndFallers':
           //queryStringParameter=queryStringParameter+"&heatMap=RisersAndFallers";
           UpdateQStringHashVariable("heatMap","rf",true);
           break;
    }
 }   
 TrendsDataOverlayType = null;
 return queryStringParameter+"&IsPrTrnds="+isPriceTrendsChecked;
  
}
/* Function used for searching the properties  */
function SearchProperties() {

    //Check the validation for the controls
    if (validateSearch() == true) {
        var isPropertySearch = false;
        var queryString = new StringBuilder();
        var querystring = "";
        var hashQueryString = window.location.hash;
        if(hashQueryString.indexOf(mapTag)>-1){
            UpdateQStringHashVariable(mapTag,'',false);
            hashQueryString = window.location.hash;
        }
        var originalQstring = window.location.search.substring(1);
        var secondarySearch = false;
        var searchType;
        var searchtext = document.getElementById("ctl00_TopSearchControl1_SearchControlTop_i0_i0_txtSearch").value.replace(/(^\s*)|(\s*$)/g, "");  
        searchtext = escape(searchtext);
        queryString.append("loc=" + searchtext);
        var chkBuyOrRent = document.getElementById('chkBuyORRent');
        var chkAmenties = document.getElementById('chkAmenties');
        var chkSchool = document.getElementById('chkSchool');
        var chkLocalInformation = document.getElementById('chkLocalInformation');
        //this functionality for price and trends
        var chkPriceAndTrends = document.getElementById('chkPriceAndTrends');
        if(chkPriceAndTrends.checked) {
          if(validatePriceAndTrend()) {
             queryString.append(FindQueryStringOfPriceAndTrends());
          }
          else{
          return false ;
          }
        }
        var newText = '';
        var isMainNavigationCheckBoxChecked = false;
        //check for rent or buy option          
        if (chkBuyOrRent.checked) {
            queryString.append(FindQueryStringVariable());
            isPropertySearch = true;
            isMainNavigationCheckBoxChecked = true;
        }
        //check if amenties and transport link options is checked
        if (chkAmenties.checked) {
         isMainNavigationCheckBoxChecked = true;
         if(hashQueryString.indexOf("poi") > -1) {
            searchType = 1;
            secondarySearch = true;
         }
        }
        var businessCategory = '';
        //for the local business directory search
         if(!TxtLocalSearchCategory) {
           TxtLocalSearchCategory = document.getElementById("ctl00_LeftNavigationControl1_txtSearchLocal");
         }
         if(TxtLocalSearchCategory.value != "" && TxtLocalSearchCategory.value != AmenitiesDefaultSearhText) {
              businessCategory = TxtLocalSearchCategory.value.replace(/(^\s*)|(\s*$)/g, "") ;
              businessCategory = escape(businessCategory);
              searchType = 1;
              secondarySearch = true;
              isBusinessDirectorySearch = true;
              queryString.append("&query="+ businessCategory);
            }
        //check if school options is checked
        if (chkSchool.checked) {
           isMainNavigationCheckBoxChecked = true;
           if(hashQueryString.indexOf("schools") > -1) { 
              searchType = 2;
              secondarySearch = true;
           }
        }
        // check if local information is checked
        if (chkLocalInformation.checked) {
            isMainNavigationCheckBoxChecked = true;
            if(hashQueryString.indexOf("overlays") > -1 || hashQueryString.indexOf("localinfo") > -1)
            {
               searchType = 3;
               secondarySearch = true;
            }
        }
        
        //// for map results if the user opens page  from the horizonal navigation links
        //// then we need to have any default value
        if(secondarySearch == false && isMainNavigationCheckBoxChecked == true )
        {
            var qString = window.location.search;
            if(qString.indexOf("search") > -1)
            {
               var amenitiesSearchType = getQStringValue("search");
               if (amenitiesSearchType && amenitiesSearchType != "") 
               {
                     secondarySearch = true;
                     switch(amenitiesSearchType)
                     {
                           case "1" :
                           {
                             if(businessCategory == '')    {
                              window.location.hash = "poi=hospitals|libraries|parking";
                              searchType = 1;
                             } 
                            break;
                           }
                           case "2" : {
                             window.location.hash = "schools=primary";
                             searchType = 2;
                             break;
                           }
                           case "3":
                           {
                             window.location.hash = "overlays=constituencies";   
                             searchType = 3;
                             break;
                           }
                           default :
                           {
                             window.location.hash = "poi=hospitals|libraries|parking";
                             searchType = 1;
                           }
                     }
               }
            }
        }  
        querystring = queryString.toString();
        if(chkPriceAndTrends.checked &&  (document.getElementById("priceTrendDisplayDiv").style.display=='block')||(document.getElementById("priceTrendDisplayDiv").style.display==''))
        {
           if(IsTrendsHeatMapLinksClicked){
                 window.location.href = ApplicationPath + "House-Prices-Trends-Rental-Yields-"+searchtext+"/PriceAndTrendProperties.aspx?" + querystring + window.location.hash;
                 return false;
           }  else {
               if(currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 ||currentPageName.indexOf("map")>-1 || currentPageName.indexOf("directions")>-1 )     {
                  window.location.href = ApplicationPath + "House-Prices-Trends-Rental-Yields-"+searchtext+"/PriceAndTrendProperties.aspx?" + querystring + window.location.hash;
                  return false;
               }
               else    {
                window.location.href = ApplicationPath + "House-Prices-Trends-Rental-Yields-"+searchtext+"/PriceAndTrends.aspx?" + querystring + window.location.hash;
                return false;
               }
           }
        }   
        //check if secondary search option is required for searching
        if (secondarySearch == true) {
            //only amenties are checked
            if (!isPropertySearch) 
            {
                if(searchType==1)
                 newText = "amenities-" + searchtext + "/map?";
                else if(searchType==2)
                 newText = "schools-" + searchtext + "/map?"; 
                else if(searchType==3)
                 newText = "localinformation-" + searchtext + "/map?";  
            }
            //both amenties and properties are checked
            else {
                if (document.getElementById('chkBuyORRent').checked == true) {
                    newText = "properties-sale-" + searchtext + "/map?";
                }
                else {
                    newText = "properties-lease-" + searchtext + "/map?"; ;
                }           
            }            
           
            var url = '';            
            if (isPropertySearch) {
                url =  newText +querystring;
            }  
            else {
                url =  newText + querystring +"&search=" + searchType;
            }
            //page does not reload when there is chnage in hash qsting only, so reloading the page forcefully 
            if( originalQstring == querystring){
                window.location.reload(true);
            }
            else{
                window.location.href = ApplicationPath+url+window.location.hash;
            }
            return false;
        }
        //when there is no seconday option selected
        else {
            if (document.getElementById('chkBuyORRent').checked == true) {
                    newText = "properties-sale-" + searchtext;
                }
                else {
                    newText = "properties-lease-" + searchtext;
                }
            if (currentPageName.toLowerCase().indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1 ||currentPageName.toLowerCase().indexOf("directions")>-1) {
               //page does not reload when there is chnage in hash qsting only, so reloading the page forcefully 
                if( originalQstring == querystring){
                    window.location.reload(true);
                }
                else{
                    window.location.href =  ApplicationPath+newText + "/map?" + querystring + window.location.hash;
                }
            }
            else {
                window.location.href = ApplicationPath+ newText + "/list?" + querystring + window.location.hash;
            }
            return false;
        }

    } //end of validate
    else {
        return false;
    }
}


/////////////////////Get the server side control reference///

/* Returns the container prefix as all controls have that on their ids */
function getCrtlPrefix(hiddenFieldID) {
    var prefix;
    var objCrtlPrefix = document.getElementById(hiddenFieldID);
    if (objCrtlPrefix)
        prefix = objCrtlPrefix.value;
    return prefix;
}

/* This function is used to read server side control values */
function readValue(ctrlName, hiddenFieldID) {
    var prefix = getCrtlPrefix(hiddenFieldID);
    var objCrtl = document.getElementById(prefix + ctrlName);
    return objCrtl;

}

/* This function is used to read the telerik control values */
function readTelerikControlValue(ctrlName, hiddenFieldID) {
    var prefix = getCrtlPrefix(hiddenFieldID);
    var objCrtl = $find(prefix + ctrlName);
    return objCrtl;

}

/////////////////////// PropertyResultlist //////////////
//////////////////////////////////////////////////////

/* This function is called when div scrollbar is moved to end and bring more record to show in the div.*/
function OnDivScroll() {
    // If there is more to show
    if (pageIndex != -1) {
         
      
        // Get contentDiv
        var contentDiv = readValue("contentDiv", "ctrlPrefixForPropertyResult");
        if (contentDiv.scrollTop < contentDiv.scrollHeight - 778)
            return;
        // Leave this method if loading is in progress
        var indicator = document.getElementById('indicator');
        if (indicator.style.display == '')
            return;
        //hide the price and trends div
       
       if( HistoricalPricesAndTrendsDiv!="undefined" && HistoricalPricesAndTrendsDiv!=null && HistoricalPricesAndTrendsDiv!=''){
         HistoricalPricesAndTrendsDiv.style.display = 'none';
       }

        // Get data for next page                
        pageIndex += 1;
        indicator.style.display = '';

        //call the ajax request to reterive the record                
        fetchMoreRecord();
    }
}

/* This function handle the reterived data */
function HandleRetrievedData(result) {
    var indicator = document.getElementById('indicator');
    var sortingIndicator = document.getElementById('sortingIndicator');
    var contentDiv = readValue("contentDiv", "ctrlPrefixForPropertyResult");

    // Parse if ajax returned data, otherwise stop calling it
    if (result.length > 0) {
        isSort = 0;

        // calculate and show total number of items
        count += pageSize;
        document.getElementById('divCount').innerHTML = count + " properties loaded."

        // iterate through result set and create a div for each item
        indicator.style.display = 'none';
        sortingIndicator.style.display = 'none';
        contentDiv.innerHTML = contentDiv.innerHTML + result;
    }
    else {
        lastPageIndex=pageIndex;
        pageIndex = -1;
        document.getElementById('divCount').innerHTML += " All properties has been loaded.";
        indicator.style.display = 'none';
    }
}

/* This function is used to get the additional record of property according to page number and page size .*/
function fetchMoreRecord() {
    var xmlHttp;
    var resultReturned;
    try {
        // Firefox, Opera 8.0+, Safari 
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer 
        try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e) {
            try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e) { alert("Your browser does not support AJAX!"); return; }
        }
    }

   queryStringParameter=updatePageIndexAndPagesize(queryStringParameter);
    // Declare a ready state change event
    xmlHttp.onreadystatechange = function() {
        if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
            resultReturned = xmlHttp.responseText;
            HandleRetrievedData(resultReturned)
        }
    };
    xmlHttp.open("GET", "GetAdditionalRecords.aspx?" + queryStringParameter + "&isSort=" + isSort + "&sortExp=" + sortExpression, true);
    xmlHttp.send(null);
}

function updatePageIndexAndPagesize(queryString)
{
 if (queryString.indexOf("&pgNo") > -1) {
        queryString = replaceQueryString(queryString, "pgNo", pageIndex);
    }
    else if(pageIndex>-1) {
        queryString = queryString + "&pgNo=" + pageIndex;
    }
    
    //set the page Size
    if (queryString.indexOf("&pgSize") > -1) {
        queryString = replaceQueryString(queryString, "pgSize", pageSize);
    }
    else if(pageSize>0) {
        queryString = queryString + "&pgSize=" + pageSize;
    }
    return queryString;
}

//check the sortOrder
function checkSortExpression()
{
   var ddlSortedBY = readTelerikControlValue("ddlSortProperty", "ctrlPrefixForPropertyResult");        
    return ddlSortedBY.get_value();
}

/* This method is used to used to sort the property accoring to selected value in the dropdown.*/
function OnClientSelectedIndexChanged(sender, eventArgs) {

    var ddlSortedBY = readTelerikControlValue("ddlSortProperty", "ctrlPrefixForPropertyResult");
    var sortingIndicator = document.getElementById('sortingIndicator');
    var contentDiv = readValue("contentDiv", "ctrlPrefixForPropertyResult");
    var selectedValue = ddlSortedBY.get_value();

    if (selectedValue != "Sort by:") {

        pageIndex = 0;
        pageSize = 15;
        count = 15;
        isSort = 1;

        if (selectedValue == "lowToHigh") {
            sortExpression = "Price Asc";
        }
        else if (selectedValue == "highToLow") {
            sortExpression = "Price Desc";
        }
        else if (selectedValue == "dateAddded") {
            sortExpression = "Added_when Desc";
        }
        contentDiv.innerHTML = "";
        sortingIndicator.style.display = '';
        fetchMoreRecord();
        isSort = 0;

    }
    else if (selectedValue == "Sort by:") {
        isSort = 0;
    }
}

//add property to favourite list
var scrollPosition ;
var ListingRkey;
var isAdd=false ;
var isDelete=false ;
function AddPropertyToFavouriteList(listingRkey)
{ 
    var indicator = document.getElementById('indicator');
    var contentDiv = readValue("contentDiv", "ctrlPrefixForPropertyResult");
    scrollPosition = contentDiv.scrollTop;        
   // contentDiv.innerHTML = "";
    indicator.style.display = '';
    isAdd=true;isDelete =false;
    ListingRkey=listingRkey;
   //check for logged in user
   queryStringParameter=UpdateQuertyStringParameters(queryStringParameter);
   AddORDeletePropertiesFromFavouriteList(listingRkey); 
}

function UpdateQuertyStringParameters(queryString)
{
  //set the ListingRkey
   if (queryString.indexOf("&ListingRkey") > -1) {
        queryString = replaceQueryString(queryString, "ListingRkey", ListingRkey);
    }
    else if(ListingRkey>0) {
        queryString = queryString + "&ListingRkey=" + ListingRkey;
    }
   
   //set the page number 
    if (queryString.indexOf("&pgNo") > -1 && pageIndex>-1) {
        queryString = replaceQueryString(queryString, "pgNo", pageIndex);
    }
    else if (queryString.indexOf("&pgNo") > -1 && pageIndex<0) {
        queryString = replaceQueryString(queryString, "pgNo", lastPageIndex);
    }
    else if(pageIndex>-1) {
        queryString = queryString + "&pgNo=" + pageIndex;
    }
    
    
    
    //set the page Size
    if (queryString.indexOf("&pgSize") > -1) {
        queryString = replaceQueryString(queryString, "pgSize", pageSize);
    }
    else if(pageSize>0) {
        queryString = queryString + "&pgSize=" + pageSize;
    }
    
    //check the property for addition or deletion    
    if(isAdd){
     if(queryString.indexOf("&IsDelete")>-1)
             { queryString =queryString.replace("&IsDelete=1",""); }
        if (queryString.indexOf("&IsAdd") > -1) {
            queryString = replaceQueryString(queryString, "IsAdd", 1);            
           }
        else {queryString = queryString + "&IsAdd=1"; }
      }
      
    if(isDelete){
       if(queryString.indexOf("&IsAdd")>-1)
             { queryString =queryString.replace("&IsAdd=1",""); }
     if (queryString.indexOf("&IsDelete") > -1) {
            queryString = replaceQueryString(queryString, "IsDelete", 1);                
            }
        else{queryString = queryString + "&IsDelete=1" ;   }
    }
    
    if (queryString.indexOf("&IsSame") > -1) {
        queryString = replaceQueryString(queryString, "IsSame", 1)
    }    
    else {queryString = queryString + "&IsSame=1" ; }
    //chech the scroll postion
    if (queryString.indexOf("&scPos") > -1) {
        queryString = replaceQueryString(queryString, "scPos", scrollPosition);
    }
    else {queryString = queryString + "&scPos=" + scrollPosition;
    }
    //queryString = queryString + "&search=1";
    return queryString ;
    
}


/* This function is used to get the additional record of property according to page number and page size .*/
function AddORDeletePropertiesFromFavouriteList(listingRkey) {
    
 //PageMethods.AddPropertyToUserFavouriteList(pageIndex,listingRkey,OnGetMessageSuccess,OnGetMessageFailure);   
    var xmlHttp;
    var resultReturned;
    try {
        // Firefox, Opera 8.0+, Safari 
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer 
        try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e) {
            try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e) { alert("Your browser does not support AJAX!"); return; }
        }
    }

    // Declare a ready state change event
    xmlHttp.onreadystatechange = function() {
        if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
            resultReturned = xmlHttp.responseText;
            FavouritePropertyResultSet(resultReturned,listingRkey);
        }
    };
    xmlHttp.open("GET", ApplicationPath+"ServerScripts/AddDeleteFavouriteProperty.aspx?" + queryStringParameter , true);
    xmlHttp.send(null);
}

/* This function handle the reterived data */
function FavouritePropertyResultSet(result,listingRkey) {
 
    var indicator = document.getElementById('indicator');
    var sortingIndicator = document.getElementById('sortingIndicator');
    var contentDiv = readValue("contentDiv", "ctrlPrefixForPropertyResult");
    var hideLinkButton  =readValue("sortPropertyDiv", "ctrlPrefixForPropertyResult");
    var queryString = window.location.search;
   // contentDiv.innerHTML="";
    if((result =="False")&& queryString.indexOf("Puid") > -1)
    { 
      window.location.href = ApplicationPath + "FavouritePropertiesPage.aspx?" + queryStringParameter;
      return;
    }
   else if(result =="False")
    { 
      window.location.href = ApplicationPath + "list?" + queryStringParameter;
      return;
    }
    // Parse if ajax returned data, otherwise stop calling it
    if (result.length > 0) {
        // iterate through result set and create a div for each item
        indicator.style.display = 'none';
        sortingIndicator.style.display = 'none';        
        var resultArray = result.split("$favouritePrptyCount="); 
         result= resultArray[0];              
         var count=0; 
         var PropertiesCount;
         if(resultArray.length>2){
          PropertiesCount= parseInt(resultArray[1]);
          count=parseInt(resultArray[2]);
         }
         else{
          PropertiesCount=parseInt(resultArray[1]);        
         }
        
        document.getElementById('ctl00_ContentPlaceHolder1_uclWatchList1_btnWatchList').value="My Watchlist ("+ PropertiesCount+")";  
        
        
        if (queryString.indexOf("Puid") > -1)
        {
         var displayRemoveAll= readValue("DeleteWatchListContent","ctrlPrefixForPropertyResult");
         var displayPropetyCount=readValue("ltPropertySearchText","ctrlPrefixForPropertyResult");
            if(PropertiesCount>0)
            {
             displayRemoveAll.Visible=true;
            } 
            else{displayRemoveAll.Visible=false;
            } 
         if(count > 1) {
            displayPropetyCount.innerHTML=count+ " Properties in Watchlist"; }
             else if(count==1) {
            displayPropetyCount.innerHTML=count+ " Property in Watchlist";  }
         else{
         displayPropetyCount.innerHTML=count+ " Properties in Watchlist"; }
        }
        
       if(result == "added"){
            document.getElementById("watchlist" + listingRkey).innerHTML = "<a onkeypress='checkKey(this)'onclick='DeletePropertyFromFavouriteList(" + listingRkey + ")' class='watchlistred'>Remove from watchlist</a>";
        //watchlistmap
        }
       else if(result == "deleted"){
            document.getElementById("watchlist" + listingRkey).innerHTML = "<a onkeypress='checkKey(this)'onclick='AddPropertyToFavouriteList(" + listingRkey + ")' class='watchlistgreen'>Save to watchlist</a>";
       }
       else{
           contentDiv.innerHTML ="";
           contentDiv.innerHTML = contentDiv.innerHTML + result;
           if(count==0){
             hideLinkButton.style.display = 'none';
             contentDiv.style.display = 'none';
             
              }
          }
       if (scrollPosition && scrollPosition > 0) {
            scrollPosition = parseInt(scrollPosition);
            contentDiv.scrollTop = scrollPosition;
            contentDiv.focus();
         }
    }
    else {
        pageIndex = -1;       
        indicator.style.display = 'none';
    }
}



//delete property from favourite list
function  DeletePropertyFromFavouriteList(listingRkey)
{
    var indicator = document.getElementById('indicator');
    var contentDiv = readValue("contentDiv", "ctrlPrefixForPropertyResult");
     scrollPosition = contentDiv.scrollTop;
     //contentDiv.innerHTML = "";
     indicator.style.display = '';
     ListingRkey =listingRkey;
     isDelete =true ;isAdd =false ;
     queryStringParameter=UpdateQuertyStringParameters(queryStringParameter);
     AddORDeletePropertiesFromFavouriteList(listingRkey);
}

////End of property result page functionality/////////////

//This block handle the property Search Control functionality/////
/////////////////////////////////////////////////////////////////

/* function to check the property search control is checked or not first time load */
function maintainTheStateOfPropertySearchControl() {
    var beds = getQStringValue("bedrooms");
    var radius = getQStringValue("rad");
    var minPrice = getQStringValue("minPrice");
    var maxPrice = getQStringValue("maxPrice");
    var houseType = getQStringValue("propty");
    var addedWhen = getQStringValue("addwhn");
    var rentbuyOption = getQStringValue("rntorbuy");

    //check with the property type dropdown list
    if (houseType && houseType != "any" && houseType != "0") {
        return true;
    }

    //check  with the search radius dropdown values        
    if (radius && radius != "any" && radius != "0") {
        return true;
    }

    //check  with the bedroom dropdown values
    if (beds && beds != "any" && beds != "0") {
        return true;
    }

    //check  with the added when dropdown values
    if (addedWhen && addedWhen != "any" && addedWhen != "0") {
        return true;
    }

    //check with buy or rent options
    if (rentbuyOption && rentbuyOption == "lease") {
        return true;
    }

    //check with the secondary options for the map i.e garages etc
    var chkAmenties = readValue("chkAmenties", "ctrlPrefixForPropertySearch");
    var elem = chkAmenties.getElementsByTagName("input");
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].checked) {
            return true;
        }
    }

    return false;
}

/* function to check the property search control is checked or not */
function IsPropertySearchControlChecked() {
    if (currentPageName.toLowerCase().indexOf("map")>-1 || currentPageName.toLowerCase().indexOf("directions")>-1 || currentPageName.toLowerCase().indexOf("priceandtrendproperties")>-1) 
    {
       if (document.getElementById("dvMapViewer")) 
       {
         if(propertyMarkers)
         {
           if(propertyMarkers.length>0)
           {
              return true;
           }
         }                        
       }  
    }
    else
    {
     // isCheckboxRentBuyClicked comes true when used clicks on buy or rent check box i.e ResetInnverValues 
     //function
     if(!isCheckboxRentBuyClicked)
     {
        var queryString = window.location.search;
        if (queryString.indexOf("rntorbuy") > -1) 
        {
           return true;
        }
      }     
    }
    //check with the secondary options for the map i.e garages etc
    var chkAmenties = readValue("chkAmenties", "ctrlPrefixForPropertySearch");
    var elem = chkAmenties.getElementsByTagName("input");
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].checked) {
            return true;
        }
    }

    //check with the property type dropdown list
    var drpPropertyType = readTelerikControlValue("drpTypes", "ctrlPrefixForPropertySearch");
    if (drpPropertyType.get_value() != "any" && drpPropertyType.get_value() != "0") {
        return true;
    }

    //check  with the search radius dropdown values
    var drpRadius = readTelerikControlValue("drpRadius", "ctrlPrefixForPropertySearch");
    if (drpRadius.get_value() != "any" && drpRadius.get_value() != "0") {
        return true;
    }

    //check  with the bedroom dropdown values
    var drpBedroom = readTelerikControlValue("drpBedroom", "ctrlPrefixForPropertySearch");
    if (drpBedroom.get_value() != "any" && drpBedroom.get_value() != "0") {
        return true;
    }

    //check  with the added when dropdown values
    var drpAdded = readTelerikControlValue("drpAdded", "ctrlPrefixForPropertySearch");
    if (drpAdded.get_value() != "any" && drpAdded.get_value() != "0") {
        return true;
    }

    //check with buy or rent options
    var rdolistId = readValue("selectbuyRent", "ctrlPrefixForPropertySearch");
    var elem = rdolistId.getElementsByTagName("input");
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].checked && i == 1) {
            return true;
        }
    }

    //check the price option
    for (var i = 0; i < elem.length; i++) {

        if (elem[i].checked) {
            if (i == 0)//sale
            {
                var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPropertySearch");
                var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPropertySearch");
                var chkPriceReduce = readValue("chkReducePrice", "ctrlPrefixForPropertySearch");
                if (drpMaxBudget.get_value() != "any" && drpMaxBudget.get_value() != "nm") {
                    return true;
                }
                if (drpMinBudget.get_value() != "any" && drpMinBudget.get_value() != "0") {
                    return true;
                }
                if(chkPriceReduce.checked)
                {
                 return true;
                }
            } //end of if
            if (i == 1)//for lease
            {
                var drpMinBudget = readTelerikControlValue("drpLeaseMinBudget", "ctrlPrefixForPropertySearch");
                var drpMaxBudget = readTelerikControlValue("drpLeaseMaxBudget", "ctrlPrefixForPropertySearch");

                if (drpMaxBudget.get_value() != "any" && drpMaxBudget.get_value() != "nm") {
                    return true;
                }
                if (drpMinBudget.get_value() != "any" && drpMinBudget.get_value() != "0") {
                    return true;
                }
            }
        } //end of the outer if
    } //end of the for loop        
    return false;
}

/* Reset the prices and trends functionality */

function ResetPricesAndTrendsValues()
{
 //check with the property type dropdown list
 var drpPropertyType = readTelerikControlValue("drpPricesAndTrendsFor", "ctrlPrefixForPriceAndTrends");
    if (drpPropertyType.get_value() != "any") {
        var item = drpPropertyType.findItemByValue("any");
        item.select();        
    }
    
    var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPriceAndTrends");
    var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPriceAndTrends");
    if (drpMaxBudget.get_value() != "nm"){
    var item = drpMaxBudget.findItemByValue("nm");
        item.select();
          
        }
    if (drpMinBudget.get_value() != "0"){
    var item = drpMinBudget.findItemByValue("0");
        item.select();
       
    }
    
    var drpToYear = readTelerikControlValue("drpToYear", "ctrlPrefixForPriceAndTrends");
    var drpFromYear = readTelerikControlValue("drpFromYear", "ctrlPrefixForPriceAndTrends");
    
    var drpToMonth = readTelerikControlValue("drpToMonth", "ctrlPrefixForPriceAndTrends");
    var drpFromMonth = readTelerikControlValue("drpFromMonth", "ctrlPrefixForPriceAndTrends");
    
    var d = new Date();   
    var curr_monthFrom = d.getMonth()+1;
    var curr_YearFrom=d.getFullYear()-2;
    var curr_monthTo = d.getMonth()+1;    
    var curr_YearTo=d.getFullYear();
    
    if(drpToYear.get_value() !=d.getFullYear())
    {
      var item = drpToYear.findItemByValue(d.getFullYear());
        item.select();
    
    }

   if(drpFromYear.get_value() !=d.getFullYear()-2)
    {
      var item = drpFromYear.findItemByValue(d.getFullYear()-2);
        item.select();
    
    }
     if(drpToMonth.get_value() !=d.getMonth()+1)
    {
      var item = drpToMonth.findItemByValue(d.getMonth()+1);
        item.select();
    
    }
     if(drpFromMonth.get_value() !=d.getMonth()+1)
    {
      var item = drpFromMonth.findItemByValue(d.getMonth()+1);
        item.select();
    
    }
   
}

/* Functionality to unchek the property filter search criteria */
function UncheckThePropertyFilter() {
    //Uncheck with the secondary options for the map i.e garages etc
    var chkAmenties = readValue("chkAmenties", "ctrlPrefixForPropertySearch");
    var elem = chkAmenties.getElementsByTagName("input");

    for (var i = 0; i < elem.length; i++) {
        elem[i].checked = false;
    }

    //check with the property type dropdown list
    var drpPropertyType = readTelerikControlValue("drpTypes", "ctrlPrefixForPropertySearch");
    if (drpPropertyType.get_value() != "any" && drpPropertyType.get_value() != "0") {
        var item = drpPropertyType.findItemByValue("any");
        item.select();
    }

    //check  with the search radius dropdown values
    var drpRadius = readTelerikControlValue("drpRadius", "ctrlPrefixForPropertySearch");
    if (drpRadius.get_value() != "any" && drpRadius.get_value() != "0") {
        var item = drpRadius.findItemByValue("0");
        item.select();
    }

    //check  with the bedroom dropdown values
    var drpBedroom = readTelerikControlValue("drpBedroom", "ctrlPrefixForPropertySearch");
    if (drpBedroom.get_value() != "any" && drpBedroom.get_value() != "0") {
        var item = drpBedroom.findItemByValue("any");
        item.select();
    }

    //check  with the added when dropdown values
    var drpAdded = readTelerikControlValue("drpAdded", "ctrlPrefixForPropertySearch");
    if (drpAdded.get_value() != "any" && drpAdded.get_value() != "0") {
        var item = drpAdded.findItemByValue("0");
        item.select();
    }

    //check with buy or rent options
    var rdolistId = readValue("selectbuyRent", "ctrlPrefixForPropertySearch"); // document.getElementById("<%=selectbuyRent.ClientID %>");
    var elem = rdolistId.getElementsByTagName("input");

    for (var i = 0; i < elem.length; i++) {
        if (elem[i].checked && i == 1) {
            elem[1].checked = false;
            elem[0].checked = true;
            //Show hide the div filters
            var saleDiv = document.getElementById("saleDiv");
            var leaseDiv = document.getElementById("leaseDiv");
            saleDiv.style.display = 'block';
            leaseDiv.style.display = 'none';
            //for mozilla
            saleDiv.style.visibility = 'visible';
            leaseDiv.style.visibility = 'hidden';
        }
    }

    //check the price option
    for (var i = 0; i < elem.length; i++) {

        if (elem[i].checked) {
            if (i == 0)//sale
            {
                var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPropertySearch");
                var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPropertySearch");

                if (drpMaxBudget.get_value() != "any" && drpMaxBudget.get_value() != "nm") {
                    var item = drpMaxBudget.findItemByValue("nm");
                    item.select();

                }
                if (drpMinBudget.get_value() != "any" && drpMinBudget.get_value() != "0") {
                    var item = drpMinBudget.findItemByValue("0");
                    item.select();

                }
                //Unchech the price tracking check box
                var chkPriceTracking = readValue("chkReducePrice", "ctrlPrefixForPropertySearch");
                document.getElementById("divReducePrice").style.display='block';
                chkPriceTracking.checked = false;
            }
            if (i == 1)//for lease
            {
                var drpMinBudget = readTelerikControlValue("drpLeaseMinBudget", "ctrlPrefixForPropertySearch");
                var drpMaxBudget = readTelerikControlValue("drpLeaseMaxBudget", "ctrlPrefixForPropertySearch");
                if (drpMaxBudget.get_value() != "any" && drpMaxBudget.get_value() != "nm") {
                    var item = drpMaxBudget.findItemByValue("nm");
                    item.select();
                }
                if (drpMinBudget.get_value() != "any" && drpMinBudget.get_value() != "0") {
                    var item = drpMinBudget.findItemByValue("0");
                    item.select();
                }
                document.getElementById("divReducePrice").style.display='none';
            }
        } //end of if
    } //end of for loop         

}



/* Get the querystring parameters */
function FindQueryStringVariable() {
    var queryStringParameter = ""; //new StringBuilder();
    //var searchtext = document.getElementById("ctl00_TopSearchControl1_SearchControlTop_i0_i0_txtSearch").value.replace(/(^\s*)|(\s*$)/g, "");

    //queryStringParameter = "loc=" + searchtext
    //check with buy or rent options
    var rdolistId = readValue("selectbuyRent", "ctrlPrefixForPropertySearch");
    var elem = rdolistId.getElementsByTagName("input");

    for (var i = 0; i < elem.length; i++) {
        if (elem[i].checked) {
            if (i == 0)//sale
            {

                var drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPropertySearch");
                var drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPropertySearch");
                MinimumPrice = drpMinBudget.get_value();
                MaximumPrice = drpMaxBudget.get_value()
                SaleOrLeaseOption = elem[i].value;
                queryStringParameter = queryStringParameter + "&minPrice=" + MinimumPrice;
                queryStringParameter = queryStringParameter + "&maxPrice=" + MaximumPrice;
                queryStringParameter = queryStringParameter + "&rntorbuy=" + SaleOrLeaseOption;
                
            }
            if (i == 1)//for lease
            {
                var drpMinBudget = readTelerikControlValue("drpLeaseMinBudget", "ctrlPrefixForPropertySearch");
                var drpMaxBudget = readTelerikControlValue("drpLeaseMaxBudget", "ctrlPrefixForPropertySearch");
                
                MinimumPrice = drpMinBudget.get_value();
                MaximumPrice = drpMaxBudget.get_value()
                SaleOrLeaseOption = elem[i].value;

                queryStringParameter = queryStringParameter + "&minPrice=" + MinimumPrice;
                queryStringParameter = queryStringParameter + "&maxPrice=" + MaximumPrice;
                queryStringParameter = queryStringParameter + "&rntorbuy=" +SaleOrLeaseOption;
            }
        }
    }

    //check for the reduced prices
    var chkReducePrize = readValue("chkReducePrice", "ctrlPrefixForPropertySearch");
    if (chkReducePrize.checked) {
        queryStringParameter = queryStringParameter + "&rudPr=1";
        ReducingPriceOption = 1;
    }
    else
    {
       ReducingPriceOption = 0;
    }

    //check  with the bedroom dropdown values
    var drpBedroom = readTelerikControlValue("drpBedroom", "ctrlPrefixForPropertySearch");
    BedRooms = drpBedroom.get_value();
    
    if(BedRooms!='any')    {
        //BedRooms = escape(BedRooms);
        queryStringParameter = queryStringParameter + "&bedrooms=" + BedRooms;
    }
     
    //check the property type 
    var drpPropertyType = readTelerikControlValue("drpTypes", "ctrlPrefixForPropertySearch");
    ResidenceType = drpPropertyType.get_value();
    if(ResidenceType!='any')
    queryStringParameter = queryStringParameter + "&propty=" + ResidenceType;

    //check the Added when
    var drpAdded = readTelerikControlValue("drpAdded", "ctrlPrefixForPropertySearch");
    PropertyAddedWhen = drpAdded.get_value();
    if(PropertyAddedWhen!='0')
    queryStringParameter = queryStringParameter + "&addwhn=" + PropertyAddedWhen;

    //check the Radius
    var drpRadius = readTelerikControlValue("drpRadius", "ctrlPrefixForPropertySearch");
    if(drpRadius.get_value()!='0')
    {
    queryStringParameter = queryStringParameter + "&rad=" + drpRadius.get_value();
    }


    //check with the secondary options for the map i.e garages etc
    var chkAmenties = readValue("chkAmenties", "ctrlPrefixForPropertySearch");
    var elem = chkAmenties.getElementsByTagName("input");
    
    for (var i = 0; i < elem.length; i++) {

        switch (i) {
            case 0:
                {
                    if (elem[i].checked) 
                    {
                        queryStringParameter = queryStringParameter + "&ofStpak=1";
                        StreetParkingOption = "1";
                    }
                    else
                    {
                     StreetParkingOption = "0";
                    }
                    break;
                }
            case 1:
                {
                    if (elem[i].checked) {
                        queryStringParameter = queryStringParameter + "&outdorsp=1";
                        OutDoorSpaceOption = "1";
                    }
                    else
                    {
                       OutDoorSpaceOption = "0";
                    }
                    
                    break;
                }
            case 2:
                {
                    if (elem[i].checked) {
                        queryStringParameter = queryStringParameter + "&gag=1";
                        GarageOption = "1";
                    }
                    else
                    {
                      GarageOption = "0";
                    }
                    break;
                }
            case 3:
                {
                    if (elem[i].checked) {
                        queryStringParameter = queryStringParameter + "&popuoff=1";
                        UnderContractOption = "1";
                    }
                    else
                    {
                      UnderContractOption = "0";
                    }
                    break;
                }
            case 4:
                {
                    if (elem[i].checked) {
                        queryStringParameter = queryStringParameter + "&savSrc=1";
                    }
                    break;
                }
           
        }

    }
    return queryStringParameter;
}

var selectSale = false;
var selectLease = false;

/* This function handle the price dropdown values according to (buy/rent) selection option.*/
function showHidePriceDiv(rdolistId) {

    var saleDiv = document.getElementById("saleDiv");
    var leaseDiv = document.getElementById("leaseDiv");
    var chkAmenties = readValue("chkAmenties", "ctrlPrefixForPropertySearch");
    var elem = rdolistId.getElementsByTagName("input");

    for (var i = 0; i < elem.length; i++) {
        if (elem[i].checked) {
            if (i == 0)//sale div selected
            {
                disableListItems(chkAmenties, "3", false) // Enable Property Under Offer List Item Index=3
                saleDiv.style.display = 'block';
                leaseDiv.style.display = 'none';
                //for mozilla
                saleDiv.style.visibility = 'visible';
                leaseDiv.style.visibility = 'hidden';
                selectSale = true;
                selectLease = false;
                //for reduce price
                document.getElementById("divReducePrice").style.display = '';

            }
            else if (i == 1) //lease div selected 
            {
                disableListItems(chkAmenties, "3", true) // Disable Property Under Offer List Item Index=3
                saleDiv.style.display = 'none';
                leaseDiv.style.display = 'block';
                saleDiv.style.visibility = 'hidden';
                leaseDiv.style.visibility = 'visible';
                selectLease = true;
                selectSale = false;
                //for reduce price
                document.getElementById("divReducePrice").style.display = 'none';
                readValue("chkReducePrice", "ctrlPrefixForPropertySearch").checked=false;
                
            }
        }
    } //end of for loop
}

/* This function is used for validation purpose. */
function validateSearch() {
    //var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
    var iChars = "!@#$%^&*()+=[]\\;,./{}|\":<>?";
    var emptySearhtext = "E.g. London or W6";
    var dvLocationErrorDetails = document.getElementById("dvLocationErrorDetails");
    var divLocationErrorMsg = document.getElementById("divLocationErrorMsg");
    var dvPriceErrorDetails = document.getElementById("dvPriceErrorDetails");
    var divErrorText = document.getElementById("divPriceErrorMsg");
    var searchTextObject = document.getElementById("ctl00_TopSearchControl1_SearchControlTop_i0_i0_txtSearch");
    searchtext = searchTextObject.value.replace(/(^\s*)|(\s*$)/g, "");

    drpMinBudget = readTelerikControlValue("drpSaleMinBudget", "ctrlPrefixForPropertySearch");
    drpMaxBudget = readTelerikControlValue("drpSaleMaxBudget", "ctrlPrefixForPropertySearch");

    if (selectLease) {
        drpMinBudget = readTelerikControlValue("drpLeaseMinBudget", "ctrlPrefixForPropertySearch")
        drpMaxBudget = readTelerikControlValue("drpLeaseMaxBudget", "ctrlPrefixForPropertySearch")
    }

    //if search text is not entered it will return the value false
    if (((searchtext == '') || (emptySearhtext == searchtext)) && (parseInt(drpMaxBudget.get_value()) < parseInt(drpMinBudget.get_value()))) {
        dvLocationErrorDetails.style.display = 'block';
        dvLocationErrorDetails.style.visibility = 'visible';
        divLocationErrorMsg.innerHTML = "Enter location, areacode, postcode, county or city.";
        searchTextObject.focus();
        dvPriceErrorDetails.style.display = 'block';
        dvPriceErrorDetails.style.visibility = 'visible';
        divErrorText.innerHTML = "Maximum budget should be greater than minimum budget";
        return false;
    }

    if ((searchtext == '') || (emptySearhtext == searchtext)) {
        dvLocationErrorDetails.style.display = 'block';
        dvLocationErrorDetails.style.visibility = 'visible';
        divLocationErrorMsg.innerHTML = "Enter location, areacode, postcode, county or city";
        searchTextObject.focus();
        dvPriceErrorDetails.style.display = 'none';
        dvPriceErrorDetails.style.visibility = 'hidden';
        return false;
    }

    //Check for special chars
    for (var i = 0; i < searchtext.length; i++) {
        if (iChars.indexOf(searchtext.charAt(i)) != -1) {
            dvLocationErrorDetails.style.display = 'block';
            dvLocationErrorDetails.style.visibility = 'visible';
            divLocationErrorMsg.innerHTML = "Special characters are not allowed in the search";
            searchTextObject.focus();
            dvPriceErrorDetails.style.display = 'none';
            dvPriceErrorDetails.style.visibility = 'hidden';
            return false;
        }
    }

    if (parseInt(drpMaxBudget.get_value()) < parseInt(drpMinBudget.get_value())) {
        dvPriceErrorDetails.style.display = 'block';
        dvPriceErrorDetails.style.visibility = 'visible';
        divErrorText.innerHTML = "Maximum budget should be greater than minimum budget";
        dvLocationErrorDetails.style.display = 'none';
        dvLocationErrorDetails.style.visibility = 'hidden';
        return false;
    }

    else {
        dvLocationErrorDetails.style.display = 'none';
        dvLocationErrorDetails.style.visibility = 'hidden';
        dvPriceErrorDetails.style.display = 'none';
        dvPriceErrorDetails.style.visibility = 'hidden';
        return true;
    }
}

/* This function is used to Reset the Price div at first time load */
function ResetPriceDivsVaules() {
    
    var queryString = window.location.search;
    if (queryString.indexOf("rntorbuy") > -1) {
        var propType = getQStringValue("rntorbuy");
        var saleDiv = document.getElementById("saleDiv");
        var leaseDiv = document.getElementById("leaseDiv");
        var chkParkingOption = readValue("chkAmenties", "ctrlPrefixForPropertySearch");

        if (propType == 'lease') {
            disableListItems(chkParkingOption, "3", true);
            saleDiv.style.display = 'none';
            leaseDiv.style.display = 'block';
            saleDiv.style.visibility = 'hidden';
            leaseDiv.style.visibility = 'visible';

            selectLease = true;
            selectSale = false;
            //reduce price
            document.getElementById("divReducePrice").style.display = 'none';
            readValue("chkReducePrice", "ctrlPrefixForPropertySearch").checked = false;
        }
        else {
            disableListItems(chkParkingOption, "3", false);
            saleDiv.style.display = 'block';
            leaseDiv.style.display = 'none';
            //for mozilla
            saleDiv.style.visibility = 'visible';
            leaseDiv.style.visibility = 'hidden';

            selectLease = false;
            selectSale = true;
        }
    }
}
/* For schools checkboxes
attaching the onclick event for the school type checkboxes
*/

function AttachOnClickEventForSchoolCheckboxes() {

//    if (currentPageName.toLowerCase().indexOf("map") == -1 || (!document.getElementById("dvMapViewer"))) 
//    {
        var schoolTypesDiv = document.getElementById("schoolsLocalInfo");
        var schools_types = schoolTypesDiv.getElementsByTagName("input");
        for (var i = 0; i < schools_types.length; i++) {
            var el = schools_types[i];
            if (el) {
                el.onclick = addHandlerForSchoolsTypes;
            }
        }
//    }
}
/* Function used to show as well as remove the amenities and local information */
function addHandlerForSchoolsTypes(e) {
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    var key = e.target.id.replace(/show_/, '');
    if (e.target && e.target.checked) 
    {
//        if((currentPageName.toLowerCase().indexOf("priceandtrendproperties.aspx") == -1 && currentPageName.toLowerCase().indexOf("map")== -1 && currentPageName.toLowerCase().indexOf("directions")== -1 )|| (!document.getElementById("dvMapViewer")))
//        { 
            document.getElementById("schoolsusermsg").style.display = '';
//        }
        UpdateQStringHashVariable(schoolTag,key,true);        
        if (key != "all") {
            CheckUnCheckSchoolOptions(key);
        }
        else {
            SelectDeSelectAllSchoolTypes();
        }
    }
    else {
        if (key == "all") {
            SelectDeSelectAllSchoolTypes();
        }
        else {
            document.getElementById("show_all").checked = false;
        }
        UpdateQStringHashVariable(schoolTag,key,false);
    }
}
function SelectDeSelectAllSchoolTypes() {
    var chkAllSchools = document.getElementById("show_all");
    var schoolTypesDiv = document.getElementById("schoolsLocalInfo");
    var schools_types = schoolTypesDiv.getElementsByTagName("input");
    if (chkAllSchools.checked == true) {
        for (var i = 0; i < schools_types.length; i++) {
            schools_types[i].checked = true;
        }
    }
    else {
        for (var i = 0; i < schools_types.length; i++) {
            schools_types[i].checked = false;
        }
    }
}

function CheckUnCheckSchoolOptions(key) {
    if (key != "all") {
        var chkAll = document.getElementById('show_all');
        if (chkAll) {
            if (chkAll.checked == false) {
                var allOptionsChecked = true;
                var schoolTypesDiv = document.getElementById("schoolsLocalInfo");
                var schools_types = schoolTypesDiv.getElementsByTagName("input");

                for (var i = 0; i < schools_types.length; i++) {

                    if (schools_types[i].id.indexOf('all') == -1) {
                        if (schools_types[i].checked == false) {
                            allOptionsChecked = false;
                        }
                    }
                }
                if (allOptionsChecked) {
                    chkAll.checked = true;
                    UpdateQStringHashVariable(schoolTag,"all",true);
                }

            } //// end of the if statement
        } ////end of the if statement
    } //end of the outer  most if statement
}
function CheckUnCheckSchoolOption(chkSchoolType)
{
  var isChecked=document.getElementById(chkSchoolType).checked;
  if(isChecked)
  {
    document.getElementById(chkSchoolType).checked=false;
  }
  else
  {
    document.getElementById(chkSchoolType).checked=true;
  } 
  if (currentPageName.indexOf("map")>-1 || currentPageName.indexOf("PriceAndTrendProperties.aspx")>-1  ) 
   {
      var key = chkSchoolType.replace(/show_/, '');
      if(document.getElementById(chkSchoolType).checked)
      {
        showSchools(key);
      }
      else
      {
        clearSchoolOverlays(key);
      }
   }
   
      
}

//////////////////////////////////////////////////////////////////////
////////////////Read cookies for Im alerts//////////////////////////
function ReadCookie(cookieName) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}

function isNumeric(value)
 {
    for(i=0;i<value.length;i++) 
    {  
     //check numbers between the 0 to 9
     if(!((value.charCodeAt(i)>=48) && (value.charCodeAt(i)<=57)))
     {
       return false 
      }
     }
    return true; 
}

function gotoRoutemapPage()
{
    start_loc = document.getElementById("startLocation").value.replace(/(^\s*)|(\s*$)/g, "").toLowerCase();
    via_loc = document.getElementById("viaLocation").value.replace(/(^\s*)|(\s*$)/g, "").toLowerCase();
    end_loc = document.getElementById("endLocation").value.replace(/(^\s*)|(\s*$)/g, "").toLowerCase();
    if(validateDirections() == true)
    {
        var shortest = false;
        var walking = false;
        var querystring = "";
        if(document.getElementById("style_shortest").checked)
        {
            shortest = true;
        }
         if(document.getElementById("mode_walking").checked)
        {
            walking = true;
        }
        start_loc = escape(start_loc);
        end_loc  = escape(end_loc);
        
        querystring = "sloc=" + start_loc + "&eloc=" + end_loc ;
        if(via_loc != "" && via_loc != null)
        {
            via_loc  = escape(via_loc);
            querystring += "&vloc=" + via_loc;
        }
        if(!walking)
        {
            querystring += "&shortest=" + shortest; 
        }
        querystring += "&walking=" + walking;
        
        var QueryStringVariables = window.location.search; 
        var hashQueryString = window.location.hash;
        if(hashQueryString.indexOf(mapTag)>-1){
            UpdateQStringHashVariable(mapTag,'',false);
            hashQueryString = window.location.hash;
        }
         if(QueryStringVariables.indexOf("search=")>-1)
         {
            //QueryStringVariables = QueryStringVariables.replace("&search=1","").replace("&search=3","").replace("&search=2","");
            QueryStringVariables = "";
         }
//         else if(QueryStringVariables.indexOf("?search")>-1)
//         {
//            QueryStringVariables = QueryStringVariables.replace("?search=1","").replace("?search=3","").replace("?search=2","");
//         }
         if(QueryStringVariables.indexOf("Puid")>-1)
         {
            QueryStringVariables = "";
         }
          if(QueryStringVariables.indexOf("?")>-1)
          {
                var index;
                if(QueryStringVariables.indexOf("sloc")>-1) {
                    index = QueryStringVariables.indexOf("sloc");
                    QueryStringVariables  = QueryStringVariables.substring(0,index-1);
                }
                else if(QueryStringVariables.indexOf("eloc")>-1){
                    index = QueryStringVariables.indexOf("eloc");
                    QueryStringVariables  = QueryStringVariables.substring(0,index-1);
                }
                if(QueryStringVariables == "")
                {
                  window.location.href = ApplicationPath + "directions" +QueryStringVariables+"?"+querystring + hashQueryString;
                }
                else
               {
                  window.location.href = ApplicationPath + "directions" +QueryStringVariables+"&"+querystring + hashQueryString;
               }
               return false;
          }
          
          else
          {
          window.location.href = ApplicationPath + "directions?" +querystring + hashQueryString;
          return false;
          }

     }//end of validate
     
    else {
        return false;
    }
}
function validateDirections()
{
     var iChars = "!@#$%^&*()+=[]\\;./{}|\":<>?";
     //value.replace(/(^\s*)|(\s*$)/g, "");  //document.getElementById("<%=txtSearch.ClientID %>").value.replace(/(^\s*)|(\s*$)/g, "");
     var dvDirectionsErrorDetails = document.getElementById("dvDirectionsErrorDetails");
     var divErrorText = document.getElementById("divDirectionsErrorMsg");
     
     if(!start_loc || start_loc == "")
     {
        dvDirectionsErrorDetails.style.display = "block";
        divErrorText.innerHTML = "Please enter start location";
        return false;
     } 
      //check for the special chars
     //Check for special chars for start location
    for (var i = 0; i < start_loc.length; i++) {
        if (iChars.indexOf(start_loc.charAt(i)) != -1) {
            dvDirectionsErrorDetails.style.display = "block";
            divErrorText.innerHTML = "Special characters are not allowed in start location";
            document.getElementById("startLocation").focus();
            return false;
        }
    }
    if(!end_loc || end_loc == "")
     {
        dvDirectionsErrorDetails.style.display = "block";
        divErrorText.innerHTML = "Please enter end location";
        return false;
     }
      //Check for special chars for end location
     for (var i = 0; i < end_loc.length; i++) {
        if (iChars.indexOf(end_loc.charAt(i)) != -1) {
            dvDirectionsErrorDetails.style.display = 'block';
            divErrorText.innerHTML = "Special characters are not allowed in end location."
            document.getElementById("endLocation").focus();
            return false;
        }
    }
    if(start_loc == via_loc || via_loc == end_loc)
     {
        dvDirectionsErrorDetails.style.display = "block";
        divErrorText.innerHTML = "Two consecutive points provided for the route should not be same";
        return false;
     }
     if(start_loc == end_loc && via_loc == "")
     {
        dvDirectionsErrorDetails.style.display = "block";
        divErrorText.innerHTML = "Two consecutive points provided for the route should not be same";
        return false;
     }
    
     //Check for special chars for via location
     for (var i = 0; i < via_loc.length; i++) {
        if (iChars.indexOf(via_loc.charAt(i)) != -1) {
            dvDirectionsErrorDetails.style.display = 'block';
            divErrorText.innerHTML = "Special characters are not allowed in via location."
            document.getElementById("viaLocation").focus();
            return false;
        }
    }    
 
    dvDirectionsErrorDetails.style.display = 'none';
    return true;
}
function setRPlannerQstringValues()
{
    var queryString = window.location.search;
    Start_Location=getQStringValue("sloc");
    End_Location=getQStringValue("eloc");
    Via_Location=getQStringValue("vloc");
    //shortest---shortest or quickest true false
    Shortest = getQStringValue("shortest");
     if(!Shortest || Shortest == "")
    {
        Shortest = "false";
    }
    //mode--driving,walking true false
    Walking = getQStringValue("walking");
     if(!Walking || Walking == "")
    {
        Walking = "false";
    }
    ShowDistance = "miles";    
}

function resetDirectionsOptions()
{      
    if(currentPageName.indexOf('directions')>-1) {
          setRPlannerQstringValues();
          var location = getQStringValue("loc");
          if(IsNullOrEmpty(End_Location) && !IsNullOrEmpty(Start_Location)) {
            document.getElementById("startLocation").value = "";
          }
          else
          {
              if(location && !Start_Location )
              {
                document.getElementById("startLocation").value = location;
              }
              else if (IsNullOrEmpty(Start_Location)) 
              {        
               document.getElementById("startLocation").value = Start_Location;
              }
          }
          if (Via_Location && Via_Location != "") 
          {        
           document.getElementById("viaLocation").value = Via_Location;
          }
          if (End_Location && End_Location != "") 
          {        
           document.getElementById("endLocation").value = End_Location;
          }
          if(Shortest == "true")
          {
            document.getElementById("style_shortest").checked = true;
          }
           if(Walking == "true")
          {
            document.getElementById("mode_walking").checked = true;
            document.getElementById("style_quickest").checked = false;
            disableDrivingOptions();
          }
     } else {
        var location = getQStringValue("loc");
        if(IsNullOrEmpty(location)) {
            document.getElementById("startLocation").value = location;
        }
     }
    return false;
}
function showRouteMap()
{
    OnListMapLinkClick('map');
}
function disableDrivingOptions()
{
    document.getElementById("style_quickest").disabled = true;
    document.getElementById("style_shortest").disabled = true;
}
function enableDrivingOptions()
{
    var quickest = document.getElementById("style_quickest");
    var shortest = document.getElementById("style_shortest");
    quickest.disabled = false;
    shortest.disabled = false;
    if(!quickest.checked && !shortest.checked)
    {
        document.getElementById("style_quickest").checked = true;
    }
}
function AttachOnClickEventToshowUserMessage()
{ 
        var amenitiesDiv = document.getElementById("amentiesDiv");
        var amenities = amenitiesDiv.getElementsByTagName("input");
        for (var i = 0; i < amenities.length; i++) {
            var id = amenities[i].id;
            if(id.indexOf("btnSearchAmenities")== -1 && id.indexOf("txtSearchLocal")== -1 && id.indexOf("TextBoxWatermarkExtender1")== -1) {
            var el = amenities[i];
            if (el) {
            el.onclick = showAmenitiesUserMessage;
            }
           } 
        }

        var localInfoDiv = document.getElementById("localInformationDiv");
        var localInfo = localInfoDiv.getElementsByTagName("input");
        for (var i = 0; i < localInfo.length; i++) {
            var el = localInfo[i];
            if (el) {
                el.onclick = showLocalinfoUserMessage;
            }
        }
}

function showAmenitiesUserMessage(e) 
{
    var updateKey;
    if (!e) {
        e = window.event;
   }
    if (!e.target) {
        e.target = e.srcElement;
    }
     if (e.target && e.target.checked) 
    {        
        document.getElementById("amenitiesusermsg").style.display = '';
        UpdateQStringHashVariable(amenitiesTag,e.target.id.replace(/show_/, ''),true);
     }
      else
     {
        UpdateQStringHashVariable(amenitiesTag,e.target.id.replace(/show_/, ''),false);
     }
}   
function showLocalinfoUserMessage(e) 
{
    if (!e) {
        e = window.event;
   }
    if (!e.target) {
        e.target = e.srcElement;
    }
    var targetName = e.target.id.replace(/show_/, '');
     if (e.target && e.target.checked) {
        //hide/show the constituency party color details when different
        //options are seleted by the user from left navigation
        ShowHideCustomOverlayLegend(targetName);
        document.getElementById("localinfousermsg").style.display = '';
        if(targetName == "wikipedia") {
            UpdateQStringHashVariable(localinfoTag,"wikipedia",true);
        }
        else {
            UpdateQStringHashVariable(overlaysTag,targetName,true);
        }
     }
     else {
        if(targetName == "wikipedia") {
            UpdateQStringHashVariable(localinfoTag,'',false);
        }
     }
}  
/*Method to hide all user messgaes shown in left nav controls*/
function hideAllUserMessages()
{
    document.getElementById("amenitiesusermsg").style.display = 'none';
    document.getElementById("localinfousermsg").style.display = 'none';
    document.getElementById("schoolsusermsg").style.display = 'none';
}
/* Method used to show hide the custom overlay legend */
function ShowHideCustomOverlayLegend(key) {
    switch(key)   {
         case "constituencies" :   {
            showCrimeMapKey(false);
            ShowConstituencyPartyColorDiv(true);
            break;
         }
         case "crime" :  {
            showCrimeMapKey(true);
            ShowConstituencyPartyColorDiv(false);
            break;
         }
         case "none" : {
            showCrimeMapKey(false);
            ShowConstituencyPartyColorDiv(false);
            break;
         }
    }
}



 
/*Method used to check for empty, null or undefined*/

function IsNullOrEmpty(inputValue){
 if(typeof(inputValue)=="undefined") {
   return false;
 } else if(inputValue == '' || inputValue == ' ' || inputValue == null ) {
   return false;
 } else if(inputValue.length == 0) {
   return false;
 }
 return true;
}
// Initializes a new instance of the StringBuilder class

// and appends the given value if supplied

function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.

StringBuilder.prototype.append = function (value)
{
    if (value)
    {
        this.strings.push(value);
    }
}

// Clears the string buffer

StringBuilder.prototype.clear = function ()
{
    this.strings.length = 1;
}

// Converts this instance to a String.

StringBuilder.prototype.toString = function ()
{
    return this.strings.join("");
}

/*Method used to hide or show the constituency party colors details */
function ShowConstituencyPartyColorDiv(bool)
{
 document.getElementById("constituencyPartyColorDiv").style.display = bool ? 'block' : 'none';
}

function showCrimeMapKey(bool)
{
 document.getElementById("dvCrimeMapKey").style.display = bool ? 'block' : 'none';
}
function SearchBusinessDirectoryResults()
{

 TxtLocalSearchCategory = document.getElementById("ctl00_LeftNavigationControl1_txtSearchLocal");
  var iChars = "!@#$%^&*()+=[]\\;,./{}|\":<>?";
  var amenitiesWarningMsgDiv =  document.getElementById("amenitiesusermsg"); 
  //check for blank
  if(!IsNullOrEmpty(TxtLocalSearchCategory) || TxtLocalSearchCategory.value == '' || TxtLocalSearchCategory.value == AmenitiesDefaultSearhText)
  {
     amenitiesWarningMsgDiv.style.display='block';
     amenitiesWarningMsgDiv.innerHTML ="Enter amenity name in the amenity search text box";
     TxtLocalSearchCategory.focus();
     return false;
  }
  var totalChars = TxtLocalSearchCategory.value.length;
    for (var i = 0; i < totalChars; i++) {
        if (iChars.indexOf(TxtLocalSearchCategory.value.charAt(i)) != -1) {
            amenitiesWarningMsgDiv.style.display = "block";
            amenitiesWarningMsgDiv.innerHTML = "Special characters are not allowed in amenities name";
            TxtLocalSearchCategory.focus();
            return false;
        }
    }
 amenitiesWarningMsgDiv.style.display="none";   
 isBusinessDirectorySearch = true;  
 if ((currentPageName.toLowerCase().indexOf("map") >-1 || currentPageName.toLowerCase().indexOf("priceandtrendproperties") >-1 || currentPageName.toLowerCase().indexOf("directions") >-1) && (document.getElementById("dvMapViewer")) ) 
 {
   if(IsMapVisible())
   {     
     SearchBusinessResultsWithinMapbounds();
     return false;
   }

}
return SearchProperties();
}

/* Method used to show the heat map images for trends data by redirecting */
function  ShowPricesAndTrendsOnHeatMap(heatMapType){
    IsTrendsHeatMapLinksClicked = true;
    TrendsDataOverlayType = heatMapType;
    SearchProperties();
}

/////////////////////// Historical prices //////////////
//////////////////////////////////////////////////////

/* This function is called when div scrollbar is moved to end and bring more record to show in the div.*/
function OnPriceTrendDivScroll() {
    // If there is more to show
    if (pageIndex != -1) {
        // Get contentDiv        
        var priceTrendContentDiv =readValue("priceTrendContentDiv", "ctrlPrefixForHistoricalPrices"); //document.getElementById("<%=priceTrendContentDiv.ClientID%>");
        var TrendIndicator = document.getElementById('priceTrendIndicator');      
        if (priceTrendContentDiv.scrollTop < priceTrendContentDiv.scrollHeight - 1004)
            return;           
        // Leave this method if loading is in progress
       
        if (TrendIndicator.style.display == 'block')
            return;

        // Get data for next page                
        pageIndex += 1;       
        TrendIndicator.style.display = 'block';

        //call the ajax request to reterive the record                
        fetchMoreHistoricalRecord();
    }
}

/* This function handle the reterived data */
function HandlePriceTrendRetrievedData(result) {
    var TrendIndicator = document.getElementById('priceTrendIndicator'); 
    var contentDiv = readValue("priceTrendContentDiv", "ctrlPrefixForHistoricalPrices");//document.getElementById("<%=priceTrendContentDiv.ClientID%>");

    // Parse if ajax returned data, otherwise stop calling it
    if (result.length > 0) {
   
        // iterate through result set and create a div for each item
        TrendIndicator.style.display = 'none';        
        contentDiv.innerHTML  +=  result;
      
    }
    else {
        pageIndex = -1;       
        TrendIndicator.style.display = 'none';
    }
}

/* This function is used to get the additional record of property according to page number and page size .*/
function fetchMoreHistoricalRecord() {
    var xmlHttp=null;
    var resultReturned="";
    try {
        // Firefox, Opera 8.0+, Safari d
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer 
        try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e) {
            try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e) { alert("Your browser does not support AJAX!"); return; }
        }
    }
    // Declare a ready state change event

    xmlHttp.onreadystatechange = function() {
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            resultReturned = xmlHttp.responseText;
            var resultArray = resultReturned.split("$pageindex=");
            resultReturned= resultArray[0];
            pageIndex= parseInt(resultArray[1]);
            HandlePriceTrendRetrievedData(resultReturned)
        }
    };
    xmlHttp.open("GET", "GetMoreHistoricalProperties.aspx?" + queryStringParameter + "&pgNo=" + pageIndex + "&pgSize=" + pageSize , true);
    xmlHttp.send(null);
  
}

/*set the div height dynamically.*/
function SetDivHightOnLoad(){
    var ptdiv =readValue("priceTrendContentDiv", "ctrlPrefixForHistoricalPrices");// document.getElementById("<%=priceTrendContentDiv.ClientID%>");    
    if(ptdiv)
    {
       var ptdivHeight = ptdiv.offsetHeight;        
        if(ptdivHeight > 1004)
        {
            ptdiv.className = "priceTrendDiv ofscroll";
            ptdiv.style.height = '1004px';
        }
        else
        {
            ptdiv.className = "priceTrendDiv ofhidden nobtop";
            ptdiv.style.width = '99.5%';
            ptdiv.style.height = 'auto';
        }
      }
 }
 
function SetFocusForBusinessSearchTxtBox(txtBusinessSearch, evt)  {
    if(txtBusinessSearch.value.length == 0 && evt.type == "blur")   {
       txtBusinessSearch.value = AmenitiesDefaultSearhText; 
    }
    if(txtBusinessSearch.value == AmenitiesDefaultSearhText &&  evt.type == "focus") {
      txtBusinessSearch.value=""; 
    }
}

/* Method used to get directions link */
function GoToDirectionsFromHere(PostalCode) {
    
    var queryString = unescape(window.location.search);
    var isSlocAlreadyPresent = false;
    if(queryString.indexOf("Puid")>-1 || queryString.indexOf("search=")>-1){
        queryString = queryString.substring(0,1);
    }
    else if(queryString.indexOf("sloc")>-1){
        queryString = replaceQueryString(queryString, "sloc", PostalCode);
        isSlocAlreadyPresent = true;
    }
    else{
        queryString = queryString + "&";
    }
    if(isSlocAlreadyPresent){
        window.location.href = ApplicationPath +  "directions" + queryString + window.location.hash;
    }
    else{
        window.location.href = ApplicationPath +  "directions" + queryString +"sloc="+ escape(PostalCode) + window.location.hash;
    }
    return false;
}

/* Method used to get directions link */
function GoToDirectionsFromThere(PostalCode) {
    
    var queryString = unescape(window.location.search);
     var isSlocAlreadyPresent = false;
     if(queryString.indexOf("Puid")>-1 || queryString.indexOf("search=")>-1 ){
        queryString = queryString.substring(0,1);
    }
    else if(queryString.indexOf("eloc")>-1){
        queryString = replaceQueryString(queryString, "eloc", PostalCode);
        isSlocAlreadyPresent = true;
    }
    else{
        queryString = queryString + "&";
    }
     if(isSlocAlreadyPresent){
        window.location.href = ApplicationPath +  "directions" + queryString + window.location.hash;
    }
    else{
        window.location.href = ApplicationPath +  "directions" + queryString +"eloc="+ escape(PostalCode) + window.location.hash;
    }
    return false;
}

function clearDirectionsOptions()
{
    document.getElementById("startLocation").value = '';
    document.getElementById("viaLocation").value = '';
    document.getElementById("endLocation").value = '';
    document.getElementById("mode_driving").checked = true;
    document.getElementById("style_quickest").checked = true;
    document.getElementById("style_quickest").disabled = false;
    document.getElementById("style_shortest").disabled = false;
}

/* Method used to open the property details page from the property pop of the map */
function OpenPropertyDetailsPage(id) {
    var queryString = unescape(window.location.search);
    
    if (queryString.indexOf("&IsSame") > -1) {
        queryString = replaceQueryString(queryString, "IsSame", 1)
    } else {queryString = queryString + "&IsSame=1" ;}
    
    if(queryString.indexOf('Puid')>-1 ) {
        dragSearch = false;
    } 
    if(currentPageName.toLowerCase().indexOf("priceandtrendproperties.aspx")>-1) {
        currentPageName = "pt";
        dragSearch = true;
    } else if(currentPageName.toLowerCase().indexOf("directions")> -1 ){
        currentPageName = "dr";
        dragSearch = true;
    } else if(currentPageName.toLowerCase().indexOf("map")> -1) {
        currentPageName = "map";
    }
    //set area parameter only when search by location
    if(dragSearch == true) {
        window.location.href =ApplicationPath+ "properties-detail/details.aspx" + queryString 
        + "&Id=" + id +"&area=" + dragSearch +"&p=" + currentPageName + window.location.hash;
    } else {
        window.location.href =ApplicationPath+ "properties-detail/details.aspx" + queryString 
        + "&Id=" + id +"&p=" + currentPageName + window.location.hash;
    }
}

/* Function used for remove the querystring values based on the key 
   like &loc=1
*/
function removeQStringValue(qString,field) {
    //unescape is used to decode the url %20 will be converted with space

    var arrQStrings = qString.split("&");
    var returnQString ="";
    for (i = 0; i < arrQStrings.length; i++) {
        var arrFields = arrQStrings[i].split("=");
        var key = arrFields[0].replace("?","");
        if (key != field) {
            returnQString = returnQString + '&'+arrQStrings[i];
        }
    }
    if(returnQString != "") {
        returnQString = returnQString.substring(1);
    }
    return returnQString;
}
﻿//This file is used to show the common functionality for multimap in MSN local

/****** Global Variables used through the MSN Local *********************/
var mapviewer, searcher, searcherAmenities, searcherLocalInformation,localSearcher,mapLoaderId, markers=[];

//// Variables used for various map types and other map related objects
var mapTypeWidget, panZoomWidget, overviewWidget, localInfoWidget, locationWidget;
var searchLocation,puid,getPricesAndTrendsQueryString = "", schoolLoaderId;
var isBackButtonRequired = false,mapResultDiv,navigationZoomInDiv, zoomInSchoolDiv,zoomInLocalInfoDiv;
var zoomFactor,searchType,search, newResults, dataSource, icon,currentKey,newResults = [];

//// Left navigation check boxes
var chkPricesAndTrends,chkBuyOrRent,chkDirections,chkSchools,chkLocalInformation,chkAmenities;
var poiLoaderId,propertyFinderLogo,shootHillLogo;

//// Query string Values
var queryStringBusinessCategory,queryStringPoi,queryStringLocalInfo,queryStringSchools;
var queryStringOverlays,qStringPricesAndTrendsSearch,previousOverlayKey = "";
var currentOverlay = "crime",isMapChanged = false;
var l_copyright,l_copyrightCollection,l_tilelayers,newlayer_pricesandtrends,newlayer_pricefallers;
var risersTileLayers,crimetilelayers,crimeNewLayer,constituencyNewLayer,constituencytilelayers;
var overlayMsg,trendsHeatMapTypeMsg,currentHeatMap;
var isMsgAlreadyShown = false,dragSearch = false;
var currentPageName = unescape(window.location.pathname);
var TxtLocalSearchCategory,routeMapPage,routeStepsPage; 

//// Hash query string keys for varioous datasets
var schoolTag = "schools",overlaysTag = "overlays", amenitiesTag = "poi",localinfoTag = "localinfo";
var mapTag = "map",isPropertyVisible = "0",isPTrendsVisible = "0";
var trendsHeatMapType = '', currentHeatMap,currentHeatmapHashValue;

//// Left navigation amenities and transport check boxes object references
var chkHospitals,chkRailStations,chkBusAndTrams,chkUnderground,chkParking,chkLibraries,chkWikipedia;

//// Status variables to check the loading status of various datasets over the map 
var IsBusinessResultsLoaded  = true,IsVEAmenitiesResultLoaded = true,IsSchoolsResultsLoaded = true, 
    IsPropertiesResultsLoaded = true ,IsMultimapAmenitiesResultsLoaded = true, IsWikipediaResultsLoaded = true;

//// Add pointer references for the most used functions
//// in order to increase the performance
var checkIsNullOrEmpty = IsNullOrEmpty; 
var getPropertiesOnMapDragged = SearchPropertiesInBoundaries;
var getSchoolResultsOnMapDragged = searchSchoolsWithinMapBounds;
var getAmenitiesOnMapDragged = displayCheckedAmenities;
var getQueryStringValue = getQStringValue;
var getFormattedPrice = insertCommas;
var  updateHashValueInUrl = UpdateQStringHashVariable;

//// Business results variables references
var isOnlyBusinessSearch = false,pager, pagerLinks,CurrentRecordIndex = 0,TotalEstimatedMatches = 0;
var BusinessDirectoryResults = new Array();    

//// Variables used for markers of different datasets
var propertyMarkers=[], trendsPropertyMarkers=[];

//// variable used for fetching values for various search parameters on map drags 
var rentbuyOption,bedrooms_more_operator = 0;
var searchQueryString = "";
var objTrendsDiv,key;

//// References for the server side pages used with json to fetch various datasets
var VEServerScriptPageUrl =  ApplicationPath + "ServerScripts/VEWebserviceScript.aspx";
var PropertiesServerScriptPageUrl = ApplicationPath + "ServerScripts/PropertySearchScriptPage.aspx";
var AmenitiesScriptPageUrl = ApplicationPath + "ServerScripts/LocalInformationScriptPage.aspx";
var SchoolsServerScriptPageUrl = ApplicationPath + "ServerScripts/SchoolScriptPage.aspx";
var PropertiesServerScriptPageUrl = ApplicationPath + "ServerScripts/PropertySearchScriptPage.aspx";
var FavouritePropScriptPageUrl = ApplicationPath+"ServerScripts/AddDeleteFavouriteProperty.aspx";

//// Various icons references used over the map
var imgProperty = new MMIcon(ImagePath + 'marker.png');
imgProperty.iconSize = new MMDimensions(25, 25);
imgProperty.groupName = 'properties';

var imgHistoricPrice = new MMIcon(ImagePath + 'historicPriceIcon.png');
imgHistoricPrice.iconSize = new MMDimensions(27, 30);
imgHistoricPrice.groupName = 'pricesandtrends';

var imgSelectiveSchools = new MMIcon(ImagePath + 'selective_school_marker.png');
imgSelectiveSchools.iconSize = new MMDimensions(20, 23);
imgSelectiveSchools.groupName = 'schools';

var imgModernSchools = new MMIcon(ImagePath + 'modern_school_marker.png');
imgModernSchools.iconSize = new MMDimensions(20, 23);
imgModernSchools.groupName = 'schools';

var imgComprehensiveSchools = new MMIcon(ImagePath + 'comprehensive_school_marker.png');
imgComprehensiveSchools.iconSize = new MMDimensions(20, 23);
imgComprehensiveSchools.groupName = 'schools';

var imgColleges = new MMIcon(ImagePath + 'colleges_marker.png');
imgColleges.iconSize = new MMDimensions(20, 23);
imgColleges.groupName = 'schools';

var imgFurtherEducations = new MMIcon(ImagePath + 'furthereducation_marker.png');
imgFurtherEducations.iconSize = new MMDimensions(20, 23);
imgFurtherEducations.groupName = 'schools';

var imgSpecialSchool = new MMIcon(ImagePath + 'special_marker.png');
imgSpecialSchool.iconSize = new MMDimensions(20, 23);
imgSpecialSchool.groupName = 'schools';

var imgWelshSchool = new MMIcon(ImagePath + 'welsh_school_marker.png');
imgWelshSchool.iconSize = new MMDimensions(20, 23);
imgWelshSchool.groupName = 'schools';

var imgPrimarySchool = new MMIcon(ImagePath + 'primary_school_marker.png');
imgPrimarySchool.iconSize = new MMDimensions(20, 23);
imgPrimarySchool.groupName = 'schools';

var imgTubeStation = new MMIcon(ImagePath + 'TubeStationIcon.png');
imgTubeStation.iconSize = new MMDimensions(20, 23);
imgTubeStation.groupName = 'underground';

var imgRailwayStation = new MMIcon(ImagePath + 'RailIcon.png');
imgRailwayStation.iconSize = new MMDimensions(21, 23);
imgRailwayStation.groupName = 'railwayStations';

var imgCinema = new MMIcon(ImagePath + 'CInemaIcon.png');
imgCinema.iconSize = new MMDimensions(21, 23);
imgCinema.groupName = 'cinemas';

var imgParking = new MMIcon(ImagePath + 'ParkingIcon.png');
imgParking.iconSize = new MMDimensions(20, 23);
imgParking.groupName = 'parking';

var imgHospital = new MMIcon(ImagePath + 'HospitalIcon.png');
imgHospital.iconSize = new MMDimensions(21, 23);
imgHospital.groupName = 'hospitals';

var imgShopping = new MMIcon(ImagePath + 'LocalShopIcon.png');
imgShopping.iconSize = new MMDimensions(20, 23);
imgShopping.groupName = 'localShops';

var imgSupermarkets = new MMIcon(ImagePath + 'SuperMarketIcon.png');
imgSupermarkets.iconSize = new MMDimensions(21, 23);
imgSupermarkets.groupName = 'supermarkets';

var imgLibrary = new MMIcon(ImagePath + 'LibraryIcon.png');
imgLibrary.iconSize = new MMDimensions(21, 23);
imgLibrary.groupName = 'libraries';

var imgWikipedia = new MMIcon(ImagePath + 'wikipedia.gif');
imgWikipedia.iconSize = new MMDimensions(23, 26);
imgWikipedia.groupName = 'wikipedia';

var imgPublicTransport = new MMIcon(ImagePath + 'publictransport.gif');
imgPublicTransport.iconSize = new MMDimensions(16, 16);
imgPublicTransport.groupName = 'publicTransport';

var imgGym = new MMIcon(ImagePath + 'GymIcon.png');
imgGym.iconSize = new MMDimensions(21, 23);
imgGym.groupName = 'gyms';

var imgPubs = new MMIcon(ImagePath + 'PubsAndBarIcon.png');
imgPubs.iconSize = new MMDimensions(21, 23);
imgPubs.groupName = 'pubs';

//// Various datasets references for the multimap
var VEOverlayKeys = {
     supermarkets: {Keyword : 'Supermarkets', FilterValue: 11151 , icon: imgSupermarkets ,groupName : 'supermarkets'},
     pubs: {Keyword : 'Pubs', FilterValue: 11199 , icon: imgPubs ,groupName : 'pubs'},
     localShops: {Keyword : 'LocalShops', FilterValue: 12873 , icon: imgShopping,groupName : 'localShops' },
     cinemas: {Keyword : 'Cinemas', FilterValue: 10064  , icon: imgCinema ,groupName : 'cinemas'},
     gyms: {Keyword : 'Gyms', FilterValue: 11550  , icon: imgGym ,groupName : 'gyms'}
};

//// Array Used for the POI's 
var overlays = {
     parking: { dataSource: 'mm.poi.global.general.parking', icon: imgParking },
     hospitals: { dataSource: 'mm.poi.global.general.healthcare', icon: imgHospital },
     railwayStations: { dataSource: 'mm.poi.global.general.railwaystation', icon: imgRailwayStation },
     underground: { dataSource: 'mm.poi.global.general.metrostation', icon: imgTubeStation },
     libraries: { dataSource: 'mm.poi.global.general.library', icon: imgLibrary },
     publicTransport: { dataSource: 'mm.poi.global.general.publictransport', icon: imgPublicTransport }
};

//// For schools overlay datasets
var schoolOverlayKeys = {
       all: { type: 'primary|selective|modern|comprehensive|colleges|further|welsh|special'},
       primary: { type: 'Primary', icon: imgPrimarySchool},
       selective: { type: 'Secondary Selective', icon: imgSelectiveSchools},
       modern: { type: 'Secondary Modern', icon: imgModernSchools},
       comprehensive: { type: 'Secondary Comprehensive', icon: imgComprehensiveSchools},
       colleges: { type: 'Colleges', icon: imgColleges },
       further: { type: 'Further Education', icon: imgFurtherEducations},
       welsh : { type: 'Secondary Welsh', icon: imgWelshSchool},
       special: { type: 'Special', icon: imgSpecialSchool}
};

//// Heat map overlays keys
var heatMapTypes = { 
       AveragePrices  : {id :'lnkAveragePrices'},
       RentalYeilds : {id :'lnkRisesAndFallers'},
       RisesAndFallers   : {id :'lnkRentalYeilds'}
};

var allSchoolTypes = "Further Education|Secondary Selective|Secondary Modern|Colleges|Special|Primary|"
                   + "Secondary Welsh|Secondary Comprehensive";

//// For local information overlay
var localInformationOverlayKeys =   {
      wikipedia: { dataSource: 'mm.poi.global.general.wikipedia', icon: imgWikipedia }
};

//// Polygon overlays for local information heat maps
var polygonOverlayKeys = {  constituencies : {}, crime : {}, none:{}  };

/************* ************************* Global Methods ************************************/

/*  Method used for updating the hash query string updates the Hash Query String by tag and key pair.
    pass '' key for removing the tag appendflag: true for appending values, false for removal */
function UpdateQStringHashVariable(tag, key, appendFlag) {
    //in case of all schools select option
    if ((tag == schoolTag) && (key == "all")){
        if (!appendFlag){
            key = '';
        }
    }    
    //in case of local inforamtion radio buttons none handling
    if((tag == overlaysTag) && (key == "none")){
        key = '';
    }    
    var newQueryString = '';
    var qStringHashValue = window.location.hash.substring(1);    
   // qStringHashValue = qStringHashValue.substring(1);
    if(qStringHashValue != '') {
        if(qStringHashValue.indexOf(tag)>-1) {
            var arrQStringNameValues = qStringHashValue.split('&');
            var arrArrayLength = arrQStringNameValues.length;
            if(arrArrayLength > 0 ) {
                for(var i=0;i < arrArrayLength;i++){
                    if(arrQStringNameValues[i].indexOf(tag)>-1){
                         if(appendFlag) {                            
                             if (key != ''){
                                newQueryString = qStringHashValue.replace(arrQStringNameValues[i], ModifyHashQStringTagValues(arrQStringNameValues[i], tag, key));                               
                             } else {
                                newQueryString = RemoveFromHashQString(qStringHashValue, arrQStringNameValues[i], i);
                             }
                         } else {
                            var newVariableValue = arrQStringNameValues[i];
                            if(key!= ''){
                                if ((schoolTag == tag) && (arrQStringNameValues[i].indexOf("all") > -1)){
                                    newVariableValue = tag + '=' + GetAllSchoolsHashQStringValue();
                                }                                
                                if(newVariableValue.indexOf(key) > -1){
                                    newVariableValue = newVariableValue.replace(tag + '=', '');
                                    if((tag == schoolTag) || (tag == amenitiesTag)){
                                        newVariableValue = newVariableValue.replace(key + '|', '');
                                        newVariableValue = newVariableValue.replace('|'+ key + '|', '');
                                        newVariableValue = newVariableValue.replace('|'+ key, '');
                                    }
                                    newVariableValue = newVariableValue.replace(key, '');
                                    if (newVariableValue == ''){
                                        newQueryString = RemoveFromHashQString(qStringHashValue, arrQStringNameValues[i], i);
                                    } else {
                                        newQueryString = qStringHashValue.replace(arrQStringNameValues[i], tag+ '='+ newVariableValue);
                                    }
                                } else {                                    
                                    newQueryString = qStringHashValue;
                                }
                            } else {
                                newQueryString = RemoveFromHashQString(qStringHashValue, arrQStringNameValues[i], i);
                            }
                         }
                        break;
                    }
                }  
            }
        } else {
             newQueryString = (key != '') ? qStringHashValue+ '&'+ tag + '='+ key : qStringHashValue;
        }
    }else {
        if (key!= '') {
            newQueryString = tag +'=' +key;
        }
    } 
    window.location.hash= newQueryString;
}

/*** Helper function to be used inside updateHashValueInUrl**/
function ModifyHashQStringTagValues(qStringTagAndKeys,tag, key) {
    var modifyFlag = false;
    switch(tag) {
        case schoolTag:{
            
            if (key != "all"){
                modifyFlag = true;
            }            
            break;
        }
        case amenitiesTag:{
            modifyFlag = true;
            break;
        }
        default:{
            break;
        }
    }    
    if(modifyFlag){
        if (qStringTagAndKeys.indexOf(key) == -1) {
            qStringTagAndKeys = qStringTagAndKeys + '|'+ key;
         }
    }else {
        qStringTagAndKeys = tag + '='+ key;
    }
    return qStringTagAndKeys;
}

/*** Function used to removes tag from the hash qstring ****/
function RemoveFromHashQString(qStringHashValue, qStringTagAndKeys, i) {
    if(qStringHashValue.indexOf("&"+qStringTagAndKeys)>-1) {
        qStringHashValue = qStringHashValue.replace("&"+ qStringTagAndKeys, '');
    } else {
        qStringHashValue = qStringHashValue.replace(qStringTagAndKeys, '');
        if(i==0) {
          qStringHashValue = qStringHashValue.substring(1);
        }
    }
    return qStringHashValue;
}

/** Get '|' seperated list of all schools excluding 'all' **/
function GetAllSchoolsHashQStringValue() {
   var returnValue = '';
   var schoolTypes = document.getElementById("schoolsLocalInfo");
   var schoolOptions = schoolTypes.getElementsByTagName('input');
   var totalSchoolTypes = schoolOptions.length;
   var qStringValue = new StringBuilder();
   for (var j = 0; j < totalSchoolTypes; j++) {
        var temp = schoolOptions[j].id;
        qStringValue.append(temp.substring(5) + '|');
  }
  returnValue = qStringValue.toString();
  returnValue = returnValue.substring(4, returnValue.length - 1);
  return returnValue;
}

/* Method used to get the current map position i.e map type, zoom factor , lat lon 
   to add in the query string in the form of hash values
*/
function GetCurrentMapPositionProperties() {
    var latlon =  mapviewer.getCurrentPosition();
    var mapType = mapviewer.getMapType();
    var zoomFactor = mapviewer.getZoomFactor();
    return latlon.lat + "," + latlon.lon + "|" + zoomFactor + "|" + mapType;
}

/* Method used to add different map types */
function addMapTypes() {
    ////Add map type widgets
    mapTypeWidget = new MMMapTypeWidget();
    mapviewer.addWidget(mapTypeWidget);

    ////Add map Zoom in out and the pan Widget
    panZoomWidget = new MMPanZoomWidget();
    mapviewer.addWidget(panZoomWidget);

    //Add Overview widget
    overviewWidget = new MMOverviewWidget();
    mapviewer.addWidget(overviewWidget);

    //Add the widget for the local information wizard i.e multimap POIs
    //if(currentPageName.toLowerCase().indexOf("directions") == -1){
    locationWidget = new MMLocationWidget(undefined, undefined, 'altlocation');
    locationWidget.setContainer(breadCrumContainer);
    mapviewer.addWidget(locationWidget);
}

/* Method used to Hide the error msg onChange zoom or map moved*/
function hideErrorMsg() {
  errorMsgDetails.style.display = 'none';
  errorMsgDiv.innerHTML = '';
  isMsgAlreadyShown = false;
}

/* Method used to display the error */
function displayError(errMsg, bool) {
    if (dragSearch == false) {
        errorMsgDiv.innerHTML = "";
        if (bool) {
            errorMsgDetails.style.display = 'block';
            errorMsgDiv.innerHTML = errMsg;
            isMsgAlreadyShown = true;
        } else {
            errorMsgDetails.style.display = 'none';
            errorMsgDiv.innerHTML = '';
            isMsgAlreadyShown = false;
        }
    }
}

/* Common multimap event handlers */
function addCommonEventHandlers() {
    mapviewer.addEventHandler('changeZoom', onChangeZoom);
    mapviewer.addEventHandler('click', handleClick );    
    mapviewer.addEventHandler('declutterCluster', handleCluster);
    mapviewer.addEventHandler('endPan', endPan);
    mapviewer.addEventHandler('changeMapType',onChangeMapType);
    mapviewer.addEventHandler('tilesLoaded', mapLoaded);
    mapviewer.addEventHandler('closeInfoBox', closePTInfoBox ) ;
}

/* Function used to close the prices and trends pop up if open while directly 
   closing the property pop up
*/
function closePTInfoBox() {
    ClosePricesAndTrendsPopUp();
}

/* Event handler for the map changed */
function onChangeMapType(eventType, eventTarget,oldMapType,newMapType) {

 // birds eye and Arial
 if(newMapType == 256 || newMapType == 64) {
    mapviewer.setAllowedZoomFactors(19, 20);
 } else {
   mapviewer.setAllowedZoomFactors(7, 18);
 }
 if(oldMapType ==  4 && newMapType == 256 ) {
      mapviewer.addEventHandler( 'tilesLoaded', birdsEyeTilesLoaded);
 } 
 
 //update only when map has been properly loaded and the 
 //and map change type event is fired
 if(typeof(oldMapType)!="undefined") {
    var key = GetCurrentMapPositionProperties();
    updateHashValueInUrl(mapTag,key,true);
 }   
}

/* Method called on click to birds eye map type */
function birdsEyeTilesLoaded () {
    mapviewer.removeEventHandler( 'tilesLoaded', birdsEyeTilesLoaded );
    hideConstituencyPopup();
    showShootHillLogo();
    ClosePricesAndTrendsPopUp();
    clearVEOverlays();
    clearAmentitiesOverlay();
    getPropertiesOnMapDragged();
    getSchoolResultsOnMapDragged();
    searchLocalInformationWithinMapBounds();      
    getAmenitiesOnMapDragged(); 
    SearchVEAmenitiesWithinMapbounds();
    SearchBusinessResultsWithinMapbounds();
   
}

/* Event Handler for the zoom factor change for map */
function onChangeZoom(type, target, startPosition, endPosition, reason) {
    // zoom is from left navigation zoom in link
    // in and out control reason is from map zoom control
    if (reason == "out-control" || reason == "in-control" || reason == "zoom" || reason.indexOf("-control")>-1) {
       dragSearch=true;
       var key = GetCurrentMapPositionProperties();
       updateHashValueInUrl(mapTag,key,true);
       searchNewRecordsOnMapChanges();
       searchTrendsDataWithinMapBoundaries();
       hideErrorMsg();
    }
}

/* method to handle the end pan of the map viewer */
function endPan(eventType, eventTarget, startPosition, endPosition, reason) {
    //check  reason for end pan
    if ( reason == "overview" || reason == "Econtrol" || reason == "Scontrol" || 
         reason == "Wcontrol" || reason == "Ncontrol" || reason == "drag" )  {
        dragSearch = true;
        var key = GetCurrentMapPositionProperties();
        updateHashValueInUrl(mapTag,key,true);
        searchNewRecordsOnMapChanges();
        hideErrorMsg();
        searchTrendsDataWithinMapBoundaries();
    } else if(reason == "resetposition") {
        var key = GetCurrentMapPositionProperties();
        updateHashValueInUrl(mapTag,key,true);
    }
}

/*  Method used for searching on new records for map moved 
    i.e either by the zoom level change or by map dragged or moved
*/
function searchNewRecordsOnMapChanges() {
 hideConstituencyPopup();
 showShootHillLogo();
 ClosePricesAndTrendsPopUp();
 if(CheckZoomFactor()) {
    clearVEOverlays();
    clearAmentitiesOverlay();
    getPropertiesOnMapDragged();
    getSchoolResultsOnMapDragged();
    searchLocalInformationWithinMapBounds();      
    getAmenitiesOnMapDragged(); 
 }   
 SearchVEAmenitiesWithinMapbounds();
 SearchBusinessResultsWithinMapbounds();
}

/* On click event handler for the overlay */
function handleClick( type, target, pos, arg1, arg2,arg3 ) { 
 if((crimeNewLayer) && !(target instanceof MMMarkerOverlay))   {
    hideConstituencyPopup();
    if(document.getElementById('show_crime').checked)   {
              closeInfoBox();
              loadingStatus(true);
              var popup = document.getElementById("popup");
              popup.className = "hide"; 
              var clickedPosition=mapviewer.geoPosToContainerPixels(pos);
              var peak = document.getElementById("popuppeak");
              var tempY = clickedPosition.y;
              var position = clickedPosition.toString();       
              if(clickedPosition.x > 345) {
                    clickedPosition.x = clickedPosition.x - 265;
                    popupclass = "showpopup rightpeakpopup";
              } else  {
                    popupclass = "showpopup leftpeakpopup";
              }  
              if(popup && popup != null) {
                 ShowCrimeInfoPopUp(pos.lat,pos.lon, clickedPosition.x,clickedPosition.y,tempY);
              }  
    } else if(document.getElementById('show_constituencies').checked) {
               closeInfoBox();
               loadingStatus(true);
               var popup = document.getElementById("popup");
               popup.className = "hide"; 
               var clickedPosition=mapviewer.geoPosToContainerPixels(pos);
               var peak = document.getElementById("popuppeak");
               var tempY = clickedPosition.y;
               var position = pos.toString();       
               if(clickedPosition.x > 345){
                    clickedPosition.x = clickedPosition.x - 265;
                    popupclass = "showpopup rightpeakpopup";
               } else {
                    popupclass = "showpopup leftpeakpopup";
               }  
               if(popup && popup != null){
               var popupheight = parseInt(popup.style.height);
               if((450 - clickedPosition.y) < popupheight){
                clickedPosition.y = 448 - popupheight;
               }       
               popup.style.left = clickedPosition.x + "px";
               popup.style.top = clickedPosition.y + "px"; 
               peak.style.top = ((tempY+8) - clickedPosition.y ) + "px";     
               ShowConstiuencyDetailsByLatLon(pos.lat,pos.lon);
              }
    }
 } else {
      hideConstituencyPopup();
 } 
}

/* Method used for showing the constituency details based on id */
function ShowConstiuencyDetailsByLatLon(lat,lon) {
   document.getElementById("popupdetails").innerHTML = "";
   
   // create a StringBuilder class instance
   var constDetailsHTml = new StringBuilder();
   var qStringParameters = "latitude=" + lat +"&longitude="+ lon ;
   var ajaxRequest = new ajaxObject(AmenitiesScriptPageUrl);
   ajaxRequest.callback = function(JsonString) {
     if (checkIsNullOrEmpty(JsonString)) {
          try  {
              var Constituencies = eval('(' + JsonString + ')');
              constDetailsHTml.append("<h3 class='crimepopuptitle'>Constituency information for "+ Constituencies.ConstituencyDetails[0].ConstituencyName +"</h3>");
              constDetailsHTml.append("<div id='popupinnercontent' class='ofscroll'>");
              constDetailsHTml.append("<div class='popup_dashedseparator'>");
              constDetailsHTml.append("<span style='color:#333;'><b>Constituency ruling Party</b></span><br/>");
              constDetailsHTml.append("<div style='margin:5px 0 15px;'>" + Constituencies.ConstituencyDetails[0].Party + "</div>");
              constDetailsHTml.append("</div>");
              constDetailsHTml.append("<div style='margin:10px 0 13px;'><b style='color:#333;'> Local Health Authority (PCT)</b><br/>");
              var localHealthString = Constituencies.ConstituencyDetails[0].LocalHealth;
              localHealthString = localHealthString.substring(0,localHealthString.length - 2);
              var socioEconomicString = Constituencies.ConstituencyDetails[0].SocioEconomicGroups;
              socioEconomicString = socioEconomicString.substring(0,socioEconomicString.length - 2);
              constDetailsHTml.append("<span> " + localHealthString +"</span>");
              constDetailsHTml.append("</div>");
              constDetailsHTml.append("<div><b style='color:#333;'> Socio/Economic group(s)</b><br/>");
              constDetailsHTml.append("<span> " + socioEconomicString +"</span>");
              constDetailsHTml.append("</div></div>");
            }  catch (err) { }   
        }
       
        document.getElementById("popupdetails").innerHTML = constDetailsHTml.toString();       
        var innerContent = document.getElementById("popupinnercontent");
        loadingStatus(false); 
        if(innerContent)  {                   
            document.getElementById("popup").className = popupclass;
            var innerheight = document.getElementById("popupdetails").offsetHeight;
            if(innerheight > 320)  {            
               innerContent.className = "ofscroll";
            } else {
                innerContent.className = "ofhidden";
            }
        }
    }
    ajaxRequest.update(qStringParameters);
}

/* close the opened pop up of the properties marker */
function closeInfoBox() {
    //close the property markers if any opened
    if(propertyMarkers) {
      var totalProperties = propertyMarkers.length;
      if(totalProperties > 0) {
         for (var i = 0; i < totalProperties; i++) {
              if (propertyMarkers[i].infoBoxOpened())
                    propertyMarkers[i].closeInfoBox();
         }
       }
    }
    //close the school markers if any opened
    var keys = schoolOverlayKeys["all"].type.split('|');
    var l = keys.length;
    for (var j = 0; j < l; j++) {
         //declutter the clustering according to types while removing
         var results = schoolOverlayKeys[keys[j]].results;
         if (results) {
            var totalSchools = results.length;
            for (var i = 0; i < totalSchools ; i++) {
                if (results[i].infoBoxOpened())
                    results[i].closeInfoBox();
            }
        }
    } 
}
/* Method used to show the pop up for onclick of crime image */
function ShowCrimeInfoPopUp(latitude,longitude,leftPosition,topPosition,tempY) {
   var crimeInfoPopUp = document.getElementById("popup");
   var popUpDetails = document.getElementById("popupdetails");
   popUpDetails.innerHTML = "";
   
   // create a StringBuilder class instance
   var crimeInfoDetailsHtml = new StringBuilder();
   var qStringParameters = "search=3&latitude=" + latitude + "&longitude=" + longitude;
   var ajaxRequest = new ajaxObject(AmenitiesScriptPageUrl);
   ajaxRequest.callback = function(JsonString) {
   if (checkIsNullOrEmpty(JsonString)) {
    try  {
           var CrimeData = eval('(' + JsonString + ')');
           var normalizedPostalSector = CrimeData.CrimeInformation[0].NormalizedPostalSector;
           var postalSector1 = normalizedPostalSector.substring(0,normalizedPostalSector.length-1);
           var postalSector2 = normalizedPostalSector.substring(normalizedPostalSector.length-1);
           var formattedPostalSector = postalSector1 + " " + postalSector2;
           crimeInfoDetailsHtml.append("<h3 class='crimepopuptitle'>Crime information for "+ formattedPostalSector +"</h3>");
           crimeInfoDetailsHtml.append("<div id='popupinnercontent' class='ofscroll'>");
           crimeInfoDetailsHtml.append("<div class='popup_dashedseparator'>");
           crimeInfoDetailsHtml.append("<span style='color:#333;'><b>Crime Index is "+ CrimeData.CrimeInformation[0].CrimeIndex +"</b>");
           crimeInfoDetailsHtml.append("&nbsp;<img id='imgHeatmapIndex' src='" + ImagePath + "helpIcon.gif'"
                    + " onclick='OpenCrimeStatisticsHelpPage()' onmouseover=\"showHelpText('heatmapindexhelptext','imgHeatmapIndex')\" onmouseout=\"hideHelpText('heatmapindexhelptext','imgHeatmapIndex')\" style='cursor: hand; cursor: pointer; vertical-align:text-top;' alt='Crime index' /></span>");
           //crimeInfoDetailsHtml.append("<span id='heatmapindexhelptext' style='display: none;' class='helptextBG'><span class='enhancedtext'>Crime index?</span><br /><span class='helptextpopupcontent'>" + crimeHelpText + "</span></span><br/>");
           //crimeInfoDetailsHtml.append("<div style='margin:5px 0 15px;'>&nbsp;</div>");
           crimeInfoDetailsHtml.append("</div>");
           crimeInfoDetailsHtml.append("<div style='margin:10px 0 13px;'><b style='color:#333;'> Local Health Authority (PCT)</b><br/>");
           var localHealthString = CrimeData.CrimeInformation[0].LocalHealth;
           localHealthString = localHealthString.substring(0,localHealthString.length - 2);
           var socioEconomicString =CrimeData.CrimeInformation[0].SocioEconomicGroups;
           socioEconomicString = socioEconomicString.substring(0,socioEconomicString.length - 2);
           crimeInfoDetailsHtml.append("<span> " + localHealthString +"</span>");
           crimeInfoDetailsHtml.append("</div>");
           crimeInfoDetailsHtml.append("<div><b style='color:#333;'> Socio/Economic group(s)</b><br/>");
           crimeInfoDetailsHtml.append("<span> " + socioEconomicString +"</span>");
           crimeInfoDetailsHtml.append("</div></div>");
   } catch (err) { }   
   }
       
   popUpDetails.innerHTML = crimeInfoDetailsHtml.toString();       
   var innerContent = document.getElementById("popupinnercontent");
   loadingStatus(false); 
   if(innerContent) {                   
        crimeInfoPopUp.className = popupclass;
        var innerheight = popUpDetails.offsetHeight;
             
        if(innerheight > 314) {          
           innerContent.className = "ofscroll";
        } else   {
           innerContent.className = "ofhidden";
        }
        var popupheight=parseInt(innerheight); 
        if((450 - topPosition) < popupheight) {
            topPosition = 448 - popupheight;
        }       
        crimeInfoPopUp.style.left = leftPosition + "px";
        crimeInfoPopUp.style.top = topPosition + "px"; 
        document.getElementById("popuppeak").style.top = ((tempY+8) - topPosition ) + "px";  
    }
   }
   ajaxRequest.update(qStringParameters);
}

/* Method used to initilize variables which required to initilize before checking any condition */
function InitilizeGlobalVariables() {
    pageHeaderTitle = document.getElementById("dvSearchHeading");
    errorMsgDiv =  document.getElementById("divErrorMsg");
    errorMsgDetails = document.getElementById("dvErrorDetails");
    errorImage = document.getElementById("imgError");
    trendsHeatMapTypeMsg = document.getElementById("dvHeatMapTypeMsg");
    propertyFinderLogo = document.getElementById("PFLogo");
    shootHillLogo = document.getElementById("SHLogo");  
    overlayMsg = document.getElementById("dvOverlayMsg"); 
    routeMapPage = document.getElementById("routemapwrapper");
    routeStepsPage = document.getElementById("listingContainer");  
}

/* Method used to initilize the common check boxes objects of left navigation */
function InitilizeLeftNavigationCommonObjects() {
    chkBuyOrRent=document.getElementById("chkBuyORRent");
    chkAmenities=document.getElementById("chkAmenties");
    chkLocalInformation=document.getElementById("chkLocalInformation");
    chkSchools=document.getElementById("chkSchool");
    chkDirections = document.getElementById("chkDirections");
    chkPricesAndTrends = document.getElementById("chkPriceAndTrends");
    objTrendsDiv = document.getElementById("pricesAndTrendsDiv");
    schoolLoaderId = document.getElementById("divSchoolLoader");
    mapResultDiv = document.getElementById("mapResultDiv");
    mapLoaderId = document.getElementById('dvLoading');
    
   navigationZoomInDiv = document.getElementById("dvMapZoomIn");
   zoomInSchoolDiv = document.getElementById("zoomInSchoolDiv");
   zoomInLocalInfoDiv = document.getElementById("zoomInLocalInformationDiv");
   poiLoaderId = document.getElementById("dvLoadingPoi");
   
   chkBusAndTrams = document.getElementById("show_publicTransport");               
   chkHospitals  = document.getElementById("show_hospitals");
   chkLibraries = document.getElementById("show_libraries");
   chkRailStations = document.getElementById("show_railwayStations");
   chkParking = document.getElementById("show_parking");
   chkUnderground = document.getElementById("show_underground");
   chkWikipedia = document.getElementById("show_wikipedia");
   
   
   TxtLocalSearchCategory = document.getElementById("ctl00_LeftNavigationControl1_txtSearchLocal");
   rentbuyOption = getQueryStringValue("rntorbuy");
   searchType = getQueryStringValue("search");
   queryStringPoi = getQueryStringValue("poi");
   queryStringLocalInfo = getQueryStringValue("localinfo");
   queryStringSchools = getQueryStringValue("schools");
   currentOverlay = queryStringOverlays = previousOverlayKey = getQueryStringValue("overlays");
   queryStringBusinessCategory =  getQueryStringValue("query");
   qStringPricesAndTrendsSearch =  getQueryStringValue("IsPrTrnds");
   trendsHeatMapType = getQueryStringValue("heatMap");  
    if(checkIsNullOrEmpty(trendsHeatMapType)) {
         trendsHeatMapType = trendsHeatMapType.toLowerCase();
         switch(trendsHeatMapType) {
             case 'ap':
                currentHeatMap ='AveragePrices';
                break;
             case 'ry':
                currentHeatMap ='RentalYeilds';
                break;
             case 'rf':
               currentHeatMap ='RisesAndFallers';
               break;
        }
    }
   pager = document.getElementById("pagingNavigation");
   pagerLinks = document.getElementById("pagerLinks");
}

/************* Methods used to show properties within map boundaries ***/
/* Remove the properties marker and initiale the property marker's array */
function ClearPropertiesOverlay() {
  mapviewer.declutterGroup('properties', {}, MM_DECLUTTER_NONE);
  var totalProperties = propertyMarkers.length;
  if(totalProperties > 0) {
     for (var i = 0; i < totalProperties; i++) {
            mapviewer.removeOverlay(propertyMarkers[i]);
     }
   }
   propertyMarkers = new Array();
   updateHashValueInUrl("prpty",'',false);
}  

/* Method used to Handle the Clustering of the properties */
function addPropertiesClusterGroup() {
    var clusteredPropIcon = new MMIcon(ImagePath + 'multipleMarker.png');
    clusteredPropIcon.iconSize = new MMDimensions(25, 25);
    mapviewer.declutterGroup('properties', { 'cluster_icon': clusteredPropIcon, 'hide_index': true, 
                               'index_title': '' }, MM_DECLUTTER_AGGREGATE, MM_CLUSTER_ACCURATE);
}

/* Method used to property filters on map moved */
function getSearchPropertyFilters() {
    if (!BedRooms || BedRooms == "0" || BedRooms.toLowerCase() == "any") {
         BedRooms = "-1";
    } else {
         // For option of bedrooms like one or more, two or more
         if (BedRooms) {
             var counter = BedRooms.indexOf("or");
             if (counter > 1) {
              counter = counter - 1;
              BedRooms = BedRooms.substring(0, counter);
              bedrooms_more_operator=1;
            }
         }
    }
    
    if ( (checkIsNullOrEmpty(MinimumPrice) == false ) || MinimumPrice == "0") {
          MinimumPrice = "-1";
    }
   
   if ((checkIsNullOrEmpty(MaximumPrice) == false ) || MaximumPrice == "0" || MaximumPrice == "nm") {
          MaximumPrice = "-1";
   }
    
   if(!ResidenceType || ResidenceType=="0" || ResidenceType=="any"){
          ResidenceType = "-1";
   }
    
   if (StreetParkingOption == "0" || !StreetParkingOption) {
          StreetParkingOption = "0";
   } else {
          StreetParkingOption = "1";
   }
    
   if (OutDoorSpaceOption == "0" || !OutDoorSpaceOption) {
        OutDoorSpaceOption = "0";
   } else  {
          OutDoorSpaceOption = "1";
   }
    
   if (GarageOption == "0" || !GarageOption) {
           GarageOption = "0";
   } else {
           GarageOption = "1";
   }
    
   if(!UnderContractOption || UnderContractOption=="0") {
          UnderContractOption = "0";
   }
   if (!PropertyAddedWhen || PropertyAddedWhen == "0" || PropertyAddedWhen == "any") {
          PropertyAddedWhen = "-1";
   }
   rentbuyOption = SaleOrLeaseOption;
   searchQueryString = "loc=" + searchLocation + "&bedrooms=" + BedRooms+"&auth_type=" +SaleOrLeaseOption
         + "&min_price="+MinimumPrice+"&max_price="+MaximumPrice+"&prop_type="+ResidenceType
         + "&off_street_parking="+StreetParkingOption  +"&garages="+GarageOption+"&outdoor_space="
         + OutDoorSpaceOption+"&beds_more_operator="+bedrooms_more_operator
         + "&prop_offer="+UnderContractOption+"&propertyAddedDate="+PropertyAddedWhen
         + "&radius=-1&reducing_price_option="+ReducingPriceOption;
}

/* Function used to search properties within map boundaries */
function SearchPropertiesInBoundaries() { 
 //check if properties option is checked or not
 if(chkBuyOrRent.checked && (window.location.search.indexOf('Puid')==-1)) {
    ClearPropertiesOverlay();
    addPropertiesClusterGroup();
    IsPropertiesResultsLoaded = false;
    loadingStatus(true);
    var bounds = mapviewer.getMapBounds();
    var latitude_min = bounds.getSouthWest().lat;
    var latitude_max = bounds.getNorthEast().lat;
    var longitude_min = bounds.getSouthWest().lon;
    var longitude_max = bounds.getNorthEast().lon;
    
    //Reset the Parameters
    FindQueryStringVariable();
    getSearchPropertyFilters();
    var  parameter = searchQueryString + "&latitude_min=" + latitude_min + "&latitude_max=" + latitude_max 
              + "&longitude_min=" + longitude_min + "&longitude_max=" + longitude_max+"&search=2";
    var ajaxRequest = new ajaxObject(PropertiesServerScriptPageUrl);
  
    ajaxRequest.callback = function(JsonString)  {
        if (checkIsNullOrEmpty(JsonString))  {
           try {
                var Properties = eval('(' + JsonString + ')');
                var total=Properties.Property.length;
                var getPropertyMarkers = CreatePropertyMarkers;
                for (var i = 0; i <total ; i++) {
                   getPropertyMarkers(Properties.Property[i],i);
                }
                if (propertyMarkers.length > 0) {
                    //show 'view as a list/map' links
                    if(typeof(searchType) == "undefined" && currentPageName.indexOf('map') > -1){
                         document.getElementById("ViewLink").style.display = "block";
                     }
                     updateHashValueInUrl("prpty","1",true);
                  }
           } catch(err){ } 
        }
        IsPropertiesResultsLoaded = true;
        loadingStatus(false);
    }
    ajaxRequest.update(parameter);
 }  
}

/* Method used for formatiing the price for the property */
function insertCommas(number) {
    var numStr = number.toString();
    var decPos = numStr.indexOf(".");
    if (decPos > -1) {
        number = numStr.substr(0, decPos);
    }
    number += '';
    var regex = /(\d+)(\d{3})/;
    while (regex.test(number)) {
        number = number.replace(regex, '$1' + ',' + '$2');
    }
    return number;
}

/* function used to create the properties html */
function CreatePropertyMarkers(Property,markerIndex){
    // create a StringBuilder class instance
    var html = new StringBuilder();
    var marker;
    var latitude = parseFloat(Property.Latitude);
    var longitude = parseFloat(Property.Longitude);
    var point = new MMLocation(new MMLatLon(latitude,longitude));
    if (point) {
        marker = mapviewer.createMarker(point, { 'icon': imgProperty });
    }
    html.append("<div class='MMleftArrow'></div><div class='propertypopup'>");
    var addr = '';
    var postalAddress = '';
    if (checkIsNullOrEmpty(Property.Road)) { 
       addr += Property.Road + ", "; 
    }

    if (checkIsNullOrEmpty(Property.Locality)) { 
        addr += Property.Locality + ", ";
    }

    if (checkIsNullOrEmpty(Property.Postcode)) {
        addr += Property.Postcode.toUpperCase();
        postalAddress = Property.Postcode;
    }

    html.append("<div class='popup_title'>" + addr + "</div>");
    addr = '';
    if (checkIsNullOrEmpty(Property.Price)) { 
      if(rentbuyOption=="lease") {
       if(checkIsNullOrEmpty(Property.LeasePriceTerm)) {
         if(Property.LeasePriceTerm.toLowerCase() =="weekly") {
          
           addr += "&pound;" + getFormattedPrice(Property.Price) + " pw (approx. &pound;"
                     + getFormattedPrice(Property.MonthlyLeasePrice)+" pcm) ";
         } else {
           addr += "&pound;" + getFormattedPrice(Property.MonthlyLeasePrice) + " pcm ";
         }
       } else {
           addr += "&pound;" + getFormattedPrice(Property.MonthlyLeasePrice) + " pcm ";
       }
      } else {
        addr += "&pound;" + getFormattedPrice(Property.Price) + " ";
      }
    }
    if (checkIsNullOrEmpty(Property.Subdivision)) {
        addr += Property.Subdivision + ", ";
    }

    if (checkIsNullOrEmpty(Property.SecSubdivision)) {
        addr += Property.SecSubdivision;
    }
    if (addr != '') {
        html.append("<div class='popup_price' >" + addr + "</div>");
    }

    html.append("<div>");

    if (checkIsNullOrEmpty(Property.Bedrooms) && Property.Bedrooms != '0') {
        html.append("<img alt='Beds' title='Beds' class='popupbedroomsicon' src='" + ImagePath + "bedIcon.gif'   />" 
             + Property.Bedrooms);
    }

    if (checkIsNullOrEmpty(Property.Bathrooms) && Property.Bathrooms != '0') {
        html.append("<img alt='Bathrooms' title='Bathrooms' class='popupbathroomsicon' src='" + ImagePath 
             + "bathIcon.gif'  />" + Property.Bathrooms);
    }
    html.append(" ");
    if (checkIsNullOrEmpty(Property.Description)) {
        html.append(Property.Description);
        html.append("<a  class='cursorstyle'  title='Click to view more' onclick=\"OpenPropertyDetailsPage('" 
             + Property.ListingRKey + "')\" > more</a>");
    }

    html.append("</div>");

    html.append("<div class='popupimagediv'>");
        if(rentbuyOption == "lease"){
            html.append("<div class='floatleft popupleasediv'>");

            //if (checkIsNullOrEmpty(Property.ImageURL)) {
               html.append("<a class='cursorstyle'  onclick=\"OpenPropertyDetailsPage('" + Property.ListingRKey 
                   +"')\"><img  class='popupimage'  alt='Click here to view more' src='" + 
                  Property.ImageURL + "' /></a>");
            //}

            html.append("</div>");
        } else  { // in case of sale ,generate the html for reducing price div
            html.append("<div class='floatleft reducingpricediv'>");

            //if (checkIsNullOrEmpty(Property.ImageURL)) {
                html.append("<a class='cursorstyle'  onclick=\"OpenPropertyDetailsPage('" + Property.ListingRKey 
                 +"')\"><img  class='popupimage'  alt='Click here to view more' src='" +
                 Property.ImageURL + "' /></a>");
           // }
            if(Property.ChangeIndicator == -1) {
              if(Property.PercentageChangeInSalePrice == 0){
                html.append("<div class='pricetracking'><span class='redPriceSpan'><1%</span></div>"); 
              } else {
                html.append("<div class='pricetracking'><span class='redPriceSpan'>"
                         + Property.PercentageChangeInSalePrice  +"%</span></div>"); 
              }
            }  
            html.append("</div>");
        }
    
    html.append("<div class='popupIndexDiv' style='position:relative;'> ");
    html.append("<div><a  onkeypress=\"checkKey(this)\" href=\"javascript:void(0);\""
                + "onclick=\"GetRequestDetails('" + Property.ListingRKey + "','"
                + Property.AgentID + "','" + Property.Bedrooms + "','" + Property.Price + "','" 
                + Property.Buy_Rent + "','" + searchLocation + "')\">"
                + requestDetailsText +"</a></div>");
    if(Property.isAddedAsFavourite == "1"){
            html.append("<div id='watchlistmap"+ Property.ListingRKey 
            +"'><a onkeypress='checkKey(this)'onclick='AddDeletePropertyFromFavourites(" 
            + Property.ListingRKey + ", \"delete\" ,"+ markerIndex 
            +")' class='watchlistred'>Remove from watchlist</a></div>");
    } else {
            html.append("<div id='watchlistmap"+ Property.ListingRKey 
            +"'><a onkeypress='checkKey(this)'onclick='AddDeletePropertyFromFavourites(" 
            + Property.ListingRKey + ", \"add\" ,"+ markerIndex 
            +")' class='watchlistgreen'>Save to watchlist</a></div>");
    }
    html.append("");
    if (checkIsNullOrEmpty(Property.FloodIndex)) {
        html.append("<div style='margin-top:2px;'>Flood Index is<span class='countbold' > " 
        + Property.FloodIndex+ " </span><img id='imgmapfldindex"+ Property.ListingRKey
        + "' onclick='OpenFloodRiskInformationHelpPage()' class='cursorstyle popup_help_icon'"
        + " alt='Flood' src='" + ImagePath + "helpIcon.gif' onmouseover=\"showHelpText('mapfloodindexhelptext" 
        + Property.ListingRKey+"', 'imgmapfldindex"+ Property.ListingRKey
        + "' )\" onmouseout=\"hideHelpText('mapfloodindexhelptext"
        + Property.ListingRKey+"', 'imgmapfldindex"+ Property.ListingRKey+"')\" /></div>");
    }
   
    if (checkIsNullOrEmpty(Property.CrimeIndex)) {
        html.append("<div style='margin-top:4px;'>Crime Index is<span class='countbold' > " 
        + Property.CrimeIndex + " </span><img id='imgmapCrimeindex"+ Property.ListingRKey
        + "' onclick='OpenCrimeStatisticsHelpPage()' class='cursorstyle popup_help_icon'"
        +" alt='Crime'  src='" + ImagePath + "helpIcon.gif'  onmouseover=\"showHelpText('mapcrimeindexhelptext"
        + Property.ListingRKey+"','imgmapCrimeindex"+ Property.ListingRKey
        + "')\" onmouseout=\"hideHelpText('mapcrimeindexhelptext"
        + Property.ListingRKey+"','imgmapCrimeindex"+ Property.ListingRKey+ "')\"/></div>");
    }
    html.append("<span id='mapcrimeindexhelptext"+ Property.ListingRKey
        + "' style='display: none;' class='helptextBG mapcrimeindexhelptext'>" + crimeHelpText + "</span>");
    html.append("<span id='mapfloodindexhelptext"+ Property.ListingRKey
       + "' style='display: none;' class='helptextBG mapfloodindexhelptext'>" + floodHelpText + "</span>");
    html.append("<div style='margin-top:2px;' ><a href=\"javascript:void(0);\" "
       + " onclick=\"showProcesAndTrendsData('"+Property.Postcode
       +"',event)\" >Prices, trends & rental yields</a></div>");
    html.append("</div>");
    html.append("</div>");
    html.append(" <div class='floatleft'> get directions to <a class='cursorstyle'"
       +" title='Click here to get directions' onclick=\"GoToDirectionsFromThere('"
       + postalAddress +"')\" > here</a> or <a class='cursorstyle' title='Click here to "
       + "get directions' onclick=\"GoToDirectionsFromHere('"
       + postalAddress+"')\" >from here</a></div>");
 
    html.append("<div class='popup_button'> <input type='button' id='btnViewProperty'"
         +" onclick=\"OpenPropertyDetailsPage('" + Property.ListingRKey 
         + "')\" class='button floatright' value='View details' /></div>");
    html.append("</div>");
    
    if (marker) {
        marker.setInfoBoxContent('<p>' + html.toString() + '<' + '/p>', { className: 'altinfobox' });
        propertyMarkers.push(marker);
    }
}

/* handle on the clustering of the icons */
function handleCluster(type, target, declutter_type, group_name, markers, cluster_marker, infobox_options) {
    switch (group_name) {
        case 'properties':
          infobox_options['className'] = 'altclusteredinfobox';
          break;
        case 'schools':
          infobox_options['className'] = 'popupClusteredInfobox';
          break;
        case 'pricesandtrends':  
          infobox_options['className'] = 'altclusteredinfobox';
          break;
    }
}

/* Method used to show the trends data */
function showProcesAndTrendsData(postalCode,evt) {
    var cordinates = getPageEventCoords(evt);
    var url=  ApplicationPath + "ViewPricesAndTrends.aspx";
    var qStringValues = "postalCode="+postalCode;
    var ajaxRequest = new ajaxObject(url);
    ajaxRequest.callback = function(result)  {
          if(result.length > 0)   {
            objTrendsDiv.style.display="block";
            objTrendsDiv.innerHTML = result;
            objTrendsDiv.style.left = (cordinates.left - 550) +  "px";
            objTrendsDiv.style.top  =  (cordinates.top - 43) +  "px";
          } else {
            objTrendsDiv.style.display="none";
          }
    }
    ajaxRequest.update(qStringValues); 
}

/* Method used to get the x,y position of mosue clicked
   w.r.t document
*/
function getPageEventCoords(evt) {
    var coords = {left:0, top:0};
    if (evt.pageX) {
        coords.left = evt.pageX;
        coords.top = evt.pageY;
    } else if (evt.clientX) {
        coords.left =
        evt.clientX + document.body.scrollLeft - document.body.clientLeft;
        coords.top =
        evt.clientY + document.body.scrollTop - document.body.clientTop;
        // include html element space, if applicable
        if (document.body.parentElement && document.body.parentElement.clientLeft) {
        var bodParent = document.body.parentElement;
        coords.left += bodParent.scrollLeft - bodParent.clientLeft;
        coords.top += bodParent.scrollTop - bodParent.clientTop;
        }
    }
    return coords;
}

/* Method used to hide the prices and trends div */
function ClosePricesAndTrendsPopUp() {
    if(objTrendsDiv && objTrendsDiv != null) {
      if(objTrendsDiv.style.display=="block") {
        objTrendsDiv.style.display="none";
      }  
    }
}

/* Function used to show the loading   status of the map */
function loadingStatus(bool) {
// If we're loading values we want to disable the form elements
 // and display a spinning icon to show activity
 if(bool == true ) {
    disableFormElements(true);
    disableBusinesSearchButton(true);
    mapLoaderId.style.display =  'block' ;
 } else {
     if(IsWikipediaResultsLoaded == true && IsMultimapAmenitiesResultsLoaded == true 
        && IsBusinessResultsLoaded == true && IsVEAmenitiesResultLoaded == true 
        && IsPropertiesResultsLoaded  == true && IsSchoolsResultsLoaded == true)  {
          disableFormElements(false);
          disableBusinesSearchButton(false);
          mapLoaderId.style.display =  'none' ;
    }//end of if
 }//end of else
} 
/* Method used to disable the form elements */
function disableFormElements(bool) { 
   chkBusAndTrams.disabled = bool;
   chkHospitals.disabled = bool;
   chkLibraries.disabled = bool;
   chkRailStations.disabled = bool;
   chkUnderground.disabled = bool;
   chkParking.disabled = bool;
   chkBuyOrRent.disabled = bool;
   chkDirections.disabled = bool;
   chkPricesAndTrends.disabled = bool;
   chkAmenities.disabled = bool;
   chkSchools.disabled = bool;
   chkLocalInformation.disabled = bool;
    
   //disable school options
   for (var key in schoolOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            el.disabled = bool;
        }
   }
   
   //disable the various overlay options
   for (var key in VEOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            el.disabled = bool;
        }
   }
    
   // disable the wikipedia option
   chkWikipedia.disabled = bool;
   
   // for the constituencies/flood/crime options
   for(var key in polygonOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
             el.disabled = bool;
        }//end of if
   }//end of for loop 
}

/* Method used to disable the search button while loading the results */
function disableBusinesSearchButton(bool) {
    document.getElementById("ctl00_LeftNavigationControl1_btnSearchAmenities").disabled = bool;
}

/*********** Prices and Trends Data ***************************/

/* Method used to Handle the Clustering of the properties */
function addHistoricPropClusterGroup() {
    var historicPropertiesClousterdIcon = new MMIcon(ImagePath + 'historicPriceClusterIcon.png');
    historicPropertiesClousterdIcon.iconSize = new MMDimensions(33, 36);
    mapviewer.declutterGroup('pricesandtrends', { 'cluster_icon': historicPropertiesClousterdIcon,
                     'hide_index': true,'index_title': '' }, MM_DECLUTTER_AGGREGATE, MM_CLUSTER_ACCURATE);
}

/* Function used to search prices and trends data within map boundaries */
function searchTrendsDataWithinMapBoundaries() {
 //check if properties option is checked or not
 if(chkPricesAndTrends.checked)  {
    clearTrendsPropertiesOverlay();
    addHistoricPropClusterGroup();
    loadingStatus(true);
    
    var bounds = mapviewer.getMapBounds();
    var latitude_min = bounds.getSouthWest().lat;
    
    //used to remove the bottom end markers of the map
    latitude_min = latitude_min + (Math.pow(2,Number((18 - mapviewer.getZoomFactor())))* 0.00030);
    var latitude_max = bounds.getNorthEast().lat;
    var longitude_min = bounds.getSouthWest().lon;
    var longitude_max = bounds.getNorthEast().lon;
    
    var isPartitedDataRequired = 0;
    if(mapviewer.getZoomFactor() > 14) {
       isPartitedDataRequired = 1;
    }
    
    //Reset the parameters from left navigation
    FindQueryStringOfPriceAndTrends();
    getQueryStringForTrendsData();
    var parameter = getPricesAndTrendsQueryString + "&latitude_min=" + latitude_min + "&latitude_max=" 
                + latitude_max + "&longitude_min=" + longitude_min + "&longitude_max=" + longitude_max
                +"&search=4&isPartitioned=" +isPartitedDataRequired;

    var ajaxRequest = new ajaxObject(PropertiesServerScriptPageUrl);
    ajaxRequest.callback = function(JsonString)  {
        if (checkIsNullOrEmpty(JsonString))  {
           try {
                var Properties = eval('(' + JsonString + ')');
                var total=Properties.Table.length;
                var getPropertyMarkers = getTrendsDataMarkers;
                for (var i = 0; i <total ; i++) {
                   getPropertyMarkers(Properties.Table[i]);
                }
                updateHashValueInUrl("ptrends","1",true);
           }catch(err){} 
        }
        loadingStatus(false);
    }
    ajaxRequest.update(parameter);
 }  
}

/* Function used to clear the prices and trends markers */
function clearTrendsPropertiesOverlay() {
  mapviewer.declutterGroup('pricesandtrends', {}, MM_DECLUTTER_NONE);
  var totalProperties = trendsPropertyMarkers.length;
  if(totalProperties > 0) {
     for (var i = 0; i < totalProperties; i++) {
          mapviewer.removeOverlay(trendsPropertyMarkers[i]);
     }
   }
   trendsPropertyMarkers = new Array();
   updateHashValueInUrl("ptrends",'',false);
}  

/* Method used to price and trends filters on map moved */
function getQueryStringForTrendsData() {
   // create a StringBuilder class instance
   var htmlQueryString = new StringBuilder();
   if (checkIsNullOrEmpty(searchLocation)){
      htmlQueryString.append("loc="+searchLocation);
   }
   if (checkIsNullOrEmpty(PTMaxPrice)) {
       htmlQueryString.append("&PrcTrdMaxPrc="+PTMaxPrice);
   }
   if (checkIsNullOrEmpty(PTMinPrice)) {
       htmlQueryString.append("&PrcTrdMinPrc="+PTMinPrice);
   }
   if (checkIsNullOrEmpty(PTPropertyType)) {
       htmlQueryString.append("&PrcTrndFor="+PTPropertyType);
   }
   if (checkIsNullOrEmpty(PTEndYear)) {
       htmlQueryString.append("&toYear="+PTEndYear);
   }
   if (checkIsNullOrEmpty(PTStartYear)) {
       htmlQueryString.append("&frmYear="+PTStartYear);
   }
   if (checkIsNullOrEmpty(PTEndMonth)) {
       htmlQueryString.append("&toMonth="+PTEndMonth);
   }
   if (checkIsNullOrEmpty(PTStartMonth)) {
       htmlQueryString.append("&frmMonth="+PTStartMonth);
   }
   getPricesAndTrendsQueryString = htmlQueryString.toString();
}

/* Function used to create the properties content i.e. popup infobox content html */
function getTrendsDataMarkers(Property) {
 
    // Create a StringBuilder class instance
    var html = new StringBuilder();
    html.append("<div class='MMleftArrow'></div><div class='propertypopup'>");
    var propertyAddress = '';
    var postalAddress = '';
    if (checkIsNullOrEmpty(Property.Town)) { 
       propertyAddress += Property.Town + ", "; 
    }
    if (checkIsNullOrEmpty(Property.County)) { 
       propertyAddress += Property.County + ", "; 
    }
    
    propertyAddress += Property.postalcode  ;
    html.append("<div class='popup_title'>" + propertyAddress.toUpperCase() + "</div>");
    propertyAddress = '';
    if (checkIsNullOrEmpty(Property.PrimaryAddress)) { 
       propertyAddress += Property.PrimaryAddress + ", "; 
    }
    
    if (checkIsNullOrEmpty(Property.SecondaryAddress)) { 
       propertyAddress += Property.SecondaryAddress + ", "; 
    }
    
    if (checkIsNullOrEmpty(Property.Street)) { 
       propertyAddress += Property.Street + ", "; 
    }
    
    if (checkIsNullOrEmpty(Property.District)) { 
       propertyAddress += Property.District + ", "; 
    }
    
    if (checkIsNullOrEmpty(Property.County)) { 
       propertyAddress += Property.County + ", "; 
    }
    
    propertyAddress += Property.postalcode.toUpperCase() + ", "; 
    html.append("<div class='popup_price'><span class='popup_subtitle'>Address: </span>");
    html.append(propertyAddress);
    html.append("</div>");
    html.append("<div class='popup_price'><span class='popup_subtitle'>Property type: </span>");
    html.append(Property.PropertyType);
    html.append("</div>");
    html.append("<div class='popup_price'><span class='popup_subtitle'>Last sale: </span>");
    html.append( "&pound;" + getFormattedPrice(Property.Price));
    html.append("</div>");
    html.append("<div class='popup_price'><span class='popup_subtitle'>Sale date: </span>");
    html.append(Property.date);
    html.append("</div>");
    
    html.append(" <div class='floatleft'> get directions to <a class='cursorstyle' "
               +"title='Click here to get directions' onclick=\"GoToDirectionsFromThere('"+Property.postalcode
               +"')\" > here</a> or <a class='cursorstyle' title='Click here to get directions' "
               +"onclick=\"GoToDirectionsFromHere('"+ Property.postalcode +"')\" >from here</a></div>");

    var point = new MMLocation(new MMLatLon(parseFloat(Property.Latitude),parseFloat(Property.Longitude)));
    if (point) {
        var marker = mapviewer.createMarker(point, { 'icon': imgHistoricPrice });
        marker.setInfoBoxContent('<p>' + html.toString() + '<' + '/p>', { className: 'altinfobox' });
        trendsPropertyMarkers.push(marker);
    }
}

/*************************** Schools Data Set Functions *****************/

/* Method used to fetch the records on map moved for checked options for school type */
function searchSchoolsWithinMapBounds() {
    var schoolType = "";
    for (var key in schoolOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            if (el.checked) {
                schoolType += schoolOverlayKeys[key].type + '|'
            }
        }
    }
    if (schoolType != "")  {
        if (schoolType.indexOf("all") > -1) {
          schoolType = allSchoolTypes;
    } else {
            schoolType = schoolType.substring(0, schoolType.length - 1);
    }
        
    cleanSchoolOverlays();
    IsSchoolsResultsLoaded = false;
    schoolLoadingStatus(true);
    loadingStatus(true);
    addSchoolsClusterGroup();
    var newResults = [];
    var bounds = mapviewer.getMapBounds();
    var latitude_min = bounds.getSouthWest().lat;
    var latitude_max = bounds.getNorthEast().lat;
    var longitude_min = bounds.getSouthWest().lon;
    var longitude_max = bounds.getNorthEast().lon;
    
    var newrecords =    { 
      primary: [],selective: [],modern: [],comprehensive: [],colleges: [],further: [],special: [],welsh:[] 
    };
    var parameters = "search=2&type=" + schoolType + "&latitude_min=" + latitude_min 
                     + "&latitude_max=" + latitude_max + "&longitude_min=" 
                     + longitude_min + "&longitude_max=" + longitude_max;
    var ajaxRequest = new ajaxObject(SchoolsServerScriptPageUrl);
    var markers = [];
    ajaxRequest.callback = function(JsonString) {
    if (checkIsNullOrEmpty(JsonString)) {
            var Schools = eval('(' + JsonString + ')');
            var total = Schools.School.length;
            var createSchoolHtml =  getSchoolDetailsHtml;
            var drawSchoolMarkers = createSchoolMarker;
            var html,key,point,marker;
            //for showing the school pop up 
            for (var i = 0; i < total ; i++) {
                html = createSchoolHtml(Schools.School[i]);
                key = Schools.School[i].SchoolType.toLowerCase();
                if(key !="secondary") {
                  key = key.replace("secondary","").replace("education","");
                  key = key.split(' ').join('');
                } else {
                    key="welsh";
                }
                point = new MMLocation(new MMLatLon(Schools.School[i].Latitude, Schools.School[i].Longitude));
                marker = drawSchoolMarkers(point, html, key);
                newrecords[key].push(marker);
            }
          
            if( total == 0 &&  dragSearch == false) {
              showErrorMessage("Please try changing your search to include a larger area.", true);
            }
            for (var key in newrecords) {
                schoolOverlayKeys[key].results = newrecords[key];
            }
    } else { //end of the if statement
  
         if(dragSearch == false){
           showErrorMessage("Please try changing your search to include a larger area.", true);
         }
    }
    IsSchoolsResultsLoaded = true;
    loadingStatus(false);
    schoolLoadingStatus(false);
    }
    ajaxRequest.update(parameters);

    } //end of the school types if check
}


/* Method used to create the marker for schools */
function createSchoolMarker(point, html, key) {
    var schoolmarker;
    switch (key) {
        case 'primary':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgPrimarySchool });
            break;

        case 'special':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgSpecialSchool });
            break;

        case 'comprehensive':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgComprehensiveSchools });
            break;
       
       case 'modern':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgModernSchools });
            break;
            
       case 'selective':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgSelectiveSchools });
            break;
       
       case 'further':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgFurtherEducations });
            break;
       case 'colleges':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgColleges });
            break;  
        case 'welsh':
            schoolmarker = mapviewer.createMarker(point, { 'icon': imgWelshSchool });
            break;          
    }
    
    schoolmarker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox' });
    return schoolmarker;
}

/* Method used to add group clustered for the schools */
function addSchoolsClusterGroup() {
  var clusteredSchoolIcon = new MMIcon(ImagePath + 'schools.png');
  clusteredSchoolIcon.iconSize = new MMDimensions(33,34);
  mapviewer.declutterGroup('schools', { 'cluster_icon': clusteredSchoolIcon, 'hide_index': true,
                             'index_title': '' }, MM_DECLUTTER_AGGREGATE, MM_CLUSTER_ACCURATE);
}

/* Remove the amenities and local information overlay */
function cleanSchoolOverlays() {
   mapviewer.declutterGroup('schools', {}, MM_DECLUTTER_NONE);
   var keys = schoolOverlayKeys["all"].type.split('|');
   var l = keys.length;
   for (var i = 0; i < l; ++i) {
         //declutter the clustering according to types while removing
         removeSchoolMarker(keys[i]);
   }
}

/* Method used to remove the marker from the map */
function removeSchoolMarker(key) {
    var results = schoolOverlayKeys[key].results;
    if (results) {
        var totalSchools = results.length;
        for (var i = 0; i < totalSchools ; i++) {
            mapviewer.removeOverlay(results[i]);
        }
        schoolOverlayKeys[key].results = null;
    }
}

/* Function used to show the loading   status of the map 
   while loading the school data
*/
function schoolLoadingStatus(bool) {
    schoolLoaderId.style.display = bool ? 'block' : 'none';
}



/* Method used to get the html content for the school pop up*/
function getSchoolDetailsHtml(School) {
    // create a StringBuilder class instance
    var html = new StringBuilder();
    var postalAddress ='';
    html.append("<div  class='popupContentDiv'>");
    html.append("<div class='popupHeader'>");
    html.append("<div class='MMleftArrow'></div>");
    html.append("<div class='popup_title_schools'>" + School.SchoolName + "</div>");
    html.append("</div><div class='popupContent'>");

    if (checkIsNullOrEmpty(School.SchoolType)) {
        html.append("<div class='schools_type'>" + School.SchoolType + "</div>");
    }
    html.append("<div class='marginbottom address'>");
    if (checkIsNullOrEmpty(School.Address1)) {
        html.append("<p>" + School.Address1 + "</p>");
    }
    if (checkIsNullOrEmpty(School.Address2)) {
        html.append("<p>" + School.Address2 + "</p>");
    }
    if (checkIsNullOrEmpty(School.Postalcode)) {
        html.append("<p>" + School.Postalcode.toUpperCase() + "</p>");
        postalAddress =School.Postalcode;
    }
    if (checkIsNullOrEmpty(School.Telephone)) {
        html.append("<div class='marginbottom'>Telephone: " + School.Telephone.replace(/ /g, "&nbsp;") + "</div>");
    }
    html.append("</div>");
    if (checkIsNullOrEmpty(School.NearestRailywayStation)) {
        html.append("<div><img   src='" + ApplicationPath + "include/images/railwaystation.gif' "
                 +"style='vertical-align:middle;'  alt='transport link' /> " 
                 + School.RailywayStationDistanceInMiles+ " miles " + School.NearestRailywayStation + "</div>");
    }
    if (checkIsNullOrEmpty(School.NearestTubeStation)) {
        html.append("<div  class='marginbottom'><img   src='" + ApplicationPath + "include/images/tubestation.gif' "
             +"style='vertical-align:middle;' alt='transport link' /> " + School.TubeStationDistanceInMiles 
             + " miles "  + School.NearestTubeStation + "</div>");
    }
    html.append("<div><table cellpadding='4'  cellspacing='1' width='94%' border='0'>");
    if (checkIsNullOrEmpty(School.VA)) {
        html.append(" <tr>"
                +"<td align='left' style='width:80%;padding-left:6px;'>Value Added Score (VA)</td>"
                +"<td align='center' style='width:20%'>" + School.VA + "</td>"
                +"</tr>");
    }
    if (checkIsNullOrEmpty(School.AGG)) {
        html.append("<tr>"
                   +"<td align='left' style='width:80%;padding-left:6px;'>Aggregate Score (AGG)</td>"
                   +"<td align='center' style='width:20%'>" + School.AGG + "</td>"
                   +"</tr>");
    }
    if (checkIsNullOrEmpty(School.APS)) {
        html.append("<tr>"
                 +"<td align='left' style='width:80%;padding-left:6px;'>Average Point Score (APS)</td>"
                 +"<td align='center' style='width:20%'>" + School.APS + "</td>"
                 +"</tr>");
    }
    if (checkIsNullOrEmpty(School.AgeRange)) {
        html.append("<tr>"
                    + "<td align='left' style='width:80%;padding-left:6px;'>Age Range</td>"
                    +"<td align='center' style='width:20%'>" + School.AgeRange + "</td>"
                    +"</tr>");
    }
    if (checkIsNullOrEmpty(School.NumberofPupils)) {
        html.append("<tr>"
               +"<td align='left' style='width:80%;padding-left:6px;'>Number of Pupils</td>"
               +"<td align='center' style='width:20%'>" + School.NumberofPupils + "</td>"
               +"</tr>");
    }
    html.append("</table></div>");
 
    if(isBackButtonRequired) {
      if (checkIsNullOrEmpty(searchType)&& searchType == 6) {
         html.append("<div class='popupbackbuttondiv'> "
              +"<input type='button' id='btnBack' onclick=\"RedirectToReferrerPage();\" "
              +"class='button_back' value='Back to property details' /></div>");
      }
    }
  
   html.append(" <div> get directions to <a class='cursorstyle' title='Click here to get directions' "
                +"onclick=\"GoToDirectionsFromThere('"+postalAddress +"')\" > here</a> or <a class='cursorstyle' "
                +"title='Click here to get directions' onclick=\"GoToDirectionsFromHere('"
           +postalAddress+"')\" >from here</a></div>");
    html.append("</div></div>"); //end of main outer div
    return html.toString();
}

/* Method used to hide the overlays (POIs) on the map */
function clearSchoolOverlays(key) {
    if(IsMapVisible()== true) {
        mapviewer.declutterGroup('schools', {}, MM_DECLUTTER_NONE);
        var keys;
        if (key.toLowerCase() == "all") {
            SelectDeSelectAllSchoolTypes();
            keys = schoolOverlayKeys[key].type.split('|');
            if (keys) {
            var l = keys.length;
                 if (l > 0) {
                     for (var i = 0; i < l; i++) {
                         removeSchoolMarker(keys[i]);
                     }
                 }
             }
        } else {
            document.getElementById("show_all").checked = false;
            removeSchoolMarker(key);
        }
       addSchoolsClusterGroup();
       mapviewer.redrawMap();
    } else {
        if (key.toLowerCase() == "all") {
            SelectDeSelectAllSchoolTypes();
        } else {
           document.getElementById("show_all").checked = false;
        }    
    }
    
}

/* Method used for selecting / deselecting all school type options */
function SelectDeSelectAllSchoolTypes() {
    var i;
    var chkAllSchools = document.getElementById("show_all");
    var schoolTypesDiv = document.getElementById("schoolsLocalInfo");
    var schools_types = schoolTypesDiv.getElementsByTagName("input");
    var l = schools_types.length;
    if (chkAllSchools.checked == true) {
        for (i = 0; i < l; i++) {
          schools_types[i].checked=true;
        }
    } else {
        for (i = 0; i < l; i++) {
            schools_types[i].checked = false;
        }
    }
}

/* Function used to check whether map is visible or not */
function IsMapVisible() {
    var mapStyle;
    if(currentPageName.toLowerCase().indexOf("directions") > -1 && routeMapPage && routeMapPage != null){
         mapStyle = routeMapPage.style.display;
         if(mapStyle == "") {
            mapStyle = mapResultDiv.style.display;  
         }
    } else {
         mapStyle = mapResultDiv.style.display;   
    }
    if(mapStyle == 'block' || mapStyle == "") {
        return true;
    } else {
        return false;
    }
}

/* Function used to show and hide the map where ever required */
function showMap(bool) {
    if (dragSearch == false) {
       mapResultDiv.style.display = bool ? 'block' : 'none';
    }
}

/* function used for displaying schools*/
function showSchools(key) {
if (key != "all")  {
    var el = document.getElementById('show_all');
    if (el)  {
        if (el.checked) {
            return false;
        } else  {
           //check if school is visible or not
           if(IsMapVisible()) {
             document.getElementById("schoolsusermsg").style.display = 'none';
             updateHashValueInUrl(schoolTag,key,true);
             displaySchoolOverlays(key);
           }  else {
               if(currentPageName.toLowerCase().indexOf("directions")>-1  && document.getElementById("listingContainer").style.display != "none"){
                  showDirectionsUserMessage("schools");
                  document.getElementById("show_" + key).checked = false;
                }else{
                    updateHashValueInUrl(schoolTag,key,true);
                }
                CheckUnCheckSchoolOptions(key);
           }  
        }
    }
} else {
         ////check if the map is visible or not
         if(IsMapVisible()){
            document.getElementById("schoolsusermsg").style.display = 'none';
            SelectDeSelectAllSchoolTypes();
            updateHashValueInUrl(schoolTag,key,true);
            if(CheckZoomFactor()){   
              getSchoolResultsOnMapDragged();
            }
         } else {
            if(currentPageName.toLowerCase().indexOf("directions")>-1  && document.getElementById("listingContainer").style.display != "none"){
                   showDirectionsUserMessage("schools");
                   document.getElementById("show_" + key).checked = false;
               }else{
                    SelectDeSelectAllSchoolTypes();
                    updateHashValueInUrl(schoolTag,key,true);
               }
           }  
    }
    
}

/* Method used to display the individual school type schools based on key */
function displaySchoolOverlays(key) {
 if(CheckZoomFactor()) {
    clearSchoolOverlays(key);
    CheckUnCheckSchoolOptions(key);
    IsSchoolsResultsLoaded = false;
    schoolLoadingStatus(true);
    loadingStatus(true);
    var bounds = mapviewer.getMapBounds();
    var latitude_min = bounds.getSouthWest().lat;
    var latitude_max = bounds.getNorthEast().lat;
    var longitude_min = bounds.getSouthWest().lon;
    var longitude_max = bounds.getNorthEast().lon;
    var parameters = "search=2&type=" + schoolOverlayKeys[key].type + "&latitude_min=" + latitude_min 
                   + "&latitude_max=" + latitude_max + "&longitude_min=" + longitude_min + "&longitude_max=" 
                   + longitude_max;
    var ajaxRequest = new ajaxObject(SchoolsServerScriptPageUrl);
    var markers = [];
    addSchoolsClusterGroup();
    ajaxRequest.callback = function(JsonString) {
        if (checkIsNullOrEmpty(JsonString)) {
            var Schools = eval('(' + JsonString + ')');
            var createSchoolHtml =  getSchoolDetailsHtml;
            var drawSchoolMarkers = createSchoolMarker;
            var html,point,marker ;
            var totalSchools = Schools.School.length;
            for ( var i = 0; i < totalSchools; i++) {
                 html = createSchoolHtml(Schools.School[i]);
                 point = new MMLocation(new MMLatLon(Schools.School[i].Latitude, Schools.School[i].Longitude));
                 marker = drawSchoolMarkers(point, html, key);
                 markers.push(marker);
            } //end of the for loop
            schoolOverlayKeys[key].results = markers;
        } //end of the if statement
        
        IsSchoolsResultsLoaded = true;
        loadingStatus(false);
        schoolLoadingStatus(false);
    }
    ajaxRequest.update(parameters);
 }   
}

/************* Method used to attach the onclick event handler **********/
function showDirectionsUserMessage(datasetname){
    var defaultMsg = "Please switch to map view to view ";
    switch(datasetname){
        case "amenities":
            document.getElementById("amenitiesusermsg").style.display = '';
            document.getElementById("amenitiesusermsg").innerHTML = defaultMsg + datasetname;
            break;
        case "schools":
            document.getElementById("schoolsusermsg").style.display = '';
            document.getElementById("schoolsusermsg").innerHTML = defaultMsg + datasetname;
            break;
        case "localinfo":
            document.getElementById("localinfousermsg").style.display = '';
            document.getElementById("localinfousermsg").innerHTML = defaultMsg + "local information";
            break;
        default:
            return;
    }    
}

/* Function used to attach the onlclick handler for the POIs checkboxes */
function AddHandlersForLeftNavControls() {

  //handle onclick event for the amenities check boxes from the left navigation
  // for multimap poi's
  for (var key in overlays) {
        var el = document.getElementById('show_' + key);

        if (el) {
            el.onclick = toggleOverlay;
        }
   }    
    
  //handle onclick event for the amenities check boxes from the left navigation
  // for multimap poi's
  for (var key in VEOverlayKeys) {
        var el = document.getElementById('show_' + key);

        if (el) {
            el.onclick = toggleVEOverlay;
        }
  }
   //handle onclick event for  schools
   for(var key in schoolOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            el.onclick = addHandlersForSchools;
        }
    }    
    //for local information
    for (var key in localInformationOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            el.onclick = addHandlerForLocalInformation;
        }
    }    
    
    // for the constituencies/flood/crime options
    for(var key in polygonOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            el.onclick = attachOverlayHandlers;
        }
     }
    
    //for heatmap link clicks
    for(var key in heatMapTypes)  {
        var el = document.getElementById('lnk'+ key);
        if(el) {
           el.onclick = handleHeatMaps;
         }
   }
}

/* ...............onclick handler for the various overlays......... */
function handleHeatMaps(e) {
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    //to check if directions map is displayed or not
    if(!IsMapVisible())  {
        OnListMapLinkClick('map');
    }
    if (e.target) {
        displayTrendsHeatMaps(e.target.id.replace(/lnk/, ''));
        showHideTrendHeatmapsLegend(e.target.id.replace(/lnk/, ''));
    }
}

/* Method used displays the individual overlays */
function displayTrendsHeatMaps(key) {
   currentHeatMap = key;
   showHeatMapTypeMsg(key,true);
   displayPricesAndTrendsOverlays();
   updateHashValueInUrl("heatMap",currentHeatmapHashValue,true);   
}

/* Method used to show prices and trends heat maps  */
function showHideTrendHeatmapsLegend(key)  {
   applyDefaultHeatMapLinkStyles();
   switch(key)   {
      case 'AveragePrices':
            document.getElementById("dvAvgPricesMapKey").style.display = '';
            document.getElementById("lnkAveragePrices").className = 'boldfont';
            document.getElementById("avgPriceHelptextdiv").className = 'helptextBG heatmapHelptextBold';
            break;
     case 'RentalYeilds':
            document.getElementById("dvRentalYeildsMapKey").style.display = '';
            document.getElementById("lnkRentalYeilds").className = 'boldfont';
            document.getElementById("rentalYeildHelptextdiv").className = 'helptextBG rentalYeildHelptextBold';
        break;
     case 'RisesAndFallers':
            document.getElementById("dvRisersMapKey").style.display = '';
            document.getElementById("lnkRisesAndFallers").className = 'boldfont';
            document.getElementById("riseFallHelptextdiv").className = 'helptextBG heatmapHelptextBold';
       break;
   }
}

/* This method is used for showing the message for the use to see the crime and constituency
   details for the crime and constituency overlays
*/
function showHeatMapTypeMsg(overlayType,bool) {
 if(IsMapVisible()) {
     if(bool ) {  
         trendsHeatMapTypeMsg.style.display="block";
          switch(overlayType) {
           case 'RisesAndFallers':
             trendsHeatMapTypeMsg.innerHTML="Risers & fallers as a heatmap";
             currentHeatmapHashValue = "rf";
             break;
           case 'RentalYeilds':
             trendsHeatMapTypeMsg.innerHTML="Rental yields as a heatmap";
             currentHeatmapHashValue = "ry";
             break;
           case 'AveragePrices':
             trendsHeatMapTypeMsg.innerHTML="Average prices as a heatmap";
             currentHeatmapHashValue = "ap";
             break;    
           
         }
      }  else  {
        trendsHeatMapTypeMsg.style.display="none";
      }   
  }  
}

/* Method used to search the crime data within map boundaries*/ 
function displayPricesAndTrendsOverlays() {
   //to remove all other overlays like crime or constituency, before showing heatmap overlays 
   if(chkLocalInformation.checked){
       if(document.getElementById("show_none").checked == false){ 
           var overlayInfo = document.getElementById("overlaysDiv");
           UncheckTheControlsValues(overlayInfo); 
           displayConstituencyOverlay("none");
           updateHashValueInUrl(overlaysTag,'',false);
       }
       if(chkWikipedia.checked == false){
            chkLocalInformation.checked = false;
       }
   }
   if(currentHeatMap == "RisesAndFallers"){
        mapviewer.removeOverlay(newlayer_pricesandtrends);
   } else {
        mapviewer.removeOverlay(newlayer_pricesandtrends);
        mapviewer.removeOverlay(newlayer_pricefallers);
   }
   
   mapviewer.addOverlay(newlayer_pricesandtrends);
   if(version < 7) {
          window.tile = new IETileLayerFix( mapviewer, 'MMTileLayerOverlay1' );
   }

   //add second heat map layer in case of faller and risers
   if(currentHeatMap == "RisesAndFallers")  {
      mapviewer.addOverlay(newlayer_pricefallers);
      if(version < 7) {
          window.tile = new IETileLayerFix( mapviewer, 'MMTileLayerOverlay2' );
      }  
   }
}

/* Method used to reset the heat map links with default styles */
function applyDefaultHeatMapLinkStyles() {
   document.getElementById("dvAvgPricesMapKey").style.display = 'none';
   document.getElementById("dvRentalYeildsMapKey").style.display = 'none';
   document.getElementById("dvRisersMapKey").style.display = 'none';
   document.getElementById("lnkAveragePrices").className = '';
   document.getElementById("lnkRentalYeilds").className = '';
   document.getElementById("lnkRisesAndFallers").className = '';
   document.getElementById("avgPriceHelptextdiv").className = 'helptextBG heatmapHelptext';
   document.getElementById("rentalYeildHelptextdiv").className = 'helptextBG rentalYeildHelptext';
   document.getElementById("riseFallHelptextdiv").className = 'helptextBG heatmapHelptext';
}

/* Method used to clear all the overlays i.e. markers , heat maps from the map */
function ClearAllTrendsDataOverlays() {
  clearHeatmapOverlays();  
  trendsPropertyMarkers =  new Array();  
}

/*Method to clear heatmap overlays*/
function clearHeatmapOverlays() {
    showHeatMapTypeMsg('',false);
    applyDefaultHeatMapLinkStyles();
    mapviewer.removeOverlay(newlayer_pricesandtrends);
    mapviewer.removeOverlay(newlayer_pricefallers);
    currentHeatMap = null;
    updateHashValueInUrl("heatMap",'',false);
}

/*...................End of heatmap link handlers.........*/

/* Function used tgo attach the on click evennt for polygon opverlay radio buttons*/
function attachOverlayHandlers(e){
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    if (e.target && e.target.checked) {
        var targetName = e.target.id.replace(/show_/, '');    
        //hide/show the constituency party color details when different
        //options are seleted by the user from left navigation
         if(IsMapVisible())  {
                document.getElementById("localinfousermsg").style.display = 'none';
                updateHashValueInUrl(overlaysTag,targetName,true);
                hideConstituencyPopup();
                ShowHideCustomOverlayLegend(targetName);
                //showShootHillLogo();
                displayConstituencyOverlay(targetName);
          }  else {
         if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
               showDirectionsUserMessage("localinfo");
               if(window.location.hash.indexOf('overlays') > -1){
                    //e.target.checked = false;
                    if(targetName != currentOverlay){
                        e.target.checked = false;
                        document.getElementById("show_" + currentOverlay).checked = true;
                    }
               }else{
                    e.target.checked = false;
                    document.getElementById("show_none").checked = true;
               }
           } else {
                updateHashValueInUrl(overlaysTag,targetName,true);
           }
        }
    }
}

/* Function used to show as well as remove the amenities and local information */
function addHandlersForSchools(e) {
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    var key = e.target.id.replace(/show_/, '');
    if (e.target && e.target.checked) {
        showSchools(key);
    } else {
             if(currentPageName.toLowerCase().indexOf("directions")>-1  && document.getElementById("listingContainer").style.display != "none"){
                   showDirectionsUserMessage("schools");
                   e.target.checked = true;
             } else{
                clearSchoolOverlays(key);
                 updateHashValueInUrl(schoolTag,key,false);
             }
    }
}

/* Method used to remove the marker from the map */
function removeSchoolMarker(key) {
    var results = schoolOverlayKeys[key].results;
    if (results) {
        var totalSchools = results.length;
        for (var i = 0; i < totalSchools ; i++) {
            mapviewer.removeOverlay(results[i]);
        }
        schoolOverlayKeys[key].results = null;
    }
}

/* Method used to handle the onclick event*/
function toggleVEOverlay(e) {
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    var key = e.target.id.replace(/show_/, '');
    if (e.target && e.target.checked) {
        if(IsMapVisible())  {
            document.getElementById("amenitiesusermsg").style.display = 'none';
            updateHashValueInUrl(amenitiesTag,key,true);
            showVEOverlays(key);
         } else {
           if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                showDirectionsUserMessage("amenities");
                e.target.checked = false;
           }else{
                updateHashValueInUrl(amenitiesTag,key,true);
          }
         }
    } else {
        if(IsMapVisible())  {
            updateHashValueInUrl(amenitiesTag,key,false);
            hideVEOverlays(key);
        } else {
           if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none"){
                showDirectionsUserMessage("amenities");
                e.target.checked = true;
           }else{
                updateHashValueInUrl(amenitiesTag,key,false);
          }
         }
    }
}

/* Function used to show as well as remove the amenities and local information */
function toggleOverlay(e) {
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    var key = e.target.id.replace(/show_/, '');
    if (e.target && e.target.checked) {
        
        if(IsMapVisible())  {
            document.getElementById("amenitiesusermsg").style.display = 'none';
            updateHashValueInUrl(amenitiesTag,key,true);
            displayOverlays(key);
        } else {
          if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none" ){
                showDirectionsUserMessage("amenities");
                e.target.checked = false;
          }else{
                updateHashValueInUrl(amenitiesTag,key,true);
          }
        }
    } else {
        if(IsMapVisible())  {
            updateHashValueInUrl(amenitiesTag,key,false);
            hideOverlays(key);
        }
        else{
             if(currentPageName.toLowerCase().indexOf("directions")>-1 && document.getElementById("listingContainer").style.display != "none" ){
                showDirectionsUserMessage("amenities");
                e.target.checked = true;
            } else{
                updateHashValueInUrl(amenitiesTag,key,false);
            }
        }
    }
}

/* Method used to hide the overlays (POIs) on the map */
function hideOverlays(key) {
    var results = overlays[key].results;
    if (results) {
        var totalPois = results.length;
        for (var i = 0; i < totalPois; i++) {
            mapviewer.removeOverlay(results[i]);
        }
    }
}

/* Method used to hide the overlays (POIs) on the map */
function hideVEOverlays(key) {
    var results = VEOverlayKeys[key].results;
    if (results) {
        var totalPois = results.length;
        for (var i = 0; i < totalPois; i++) {
            mapviewer.removeOverlay(results[i]);
        }
    }
}

/* Function used to remove the unchecked overlays 
   From the main check box of navigation control
*/
function removeUncheckedVEOverlays() {
    for (var key in VEOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            if (el.checked == false) {
                hideVEOverlays(key);
            }
        }//end of outer if statement
    }//end of for loop
}

/* Function used to remove the unchecked overlays 
   From the main check box of navigation control
*/
function removeUncheckedOverlays() {
    for (var key in overlays) {
        var el = document.getElementById('show_' + key);
        if (el) {
            if (el.checked == false) {
                hideOverlays(key);
            }
        }
    }
}

/* Method used to check the zoom factor */
function CheckZoomFactor() {
  zoomFactor = mapviewer.getZoomFactor();
  if (zoomFactor < 11) {
        navigationZoomInDiv.style.display = 'block';
        zoomInSchoolDiv.style.display = 'block';
        zoomInLocalInfoDiv.style.display = 'block';
        return false;
    } else {
        navigationZoomInDiv.style.display = 'none';
        zoomInSchoolDiv.style.display = 'none';
        zoomInLocalInfoDiv.style.display = 'none';
        return true;
    }
}

/*************** Local information and Amenities and Transport Links *********/

/* Method used to attach the event handler for the school type check boxes */
function addHandlerForLocalInformation(e) {
    if (!e) {
        e = window.event;
    }
    if (!e.target) {
        e.target = e.srcElement;
    }
    if (e.target && e.target.checked) {
         if(IsMapVisible())  {
            document.getElementById("localinfousermsg").style.display = 'none';
            updateHashValueInUrl(localinfoTag,"wikipedia",true);
            showLocalInformation(e.target.id.replace(/show_/, ''));
         } else {
             if(currentPageName.toLowerCase().indexOf("directions")>-1  && document.getElementById("listingContainer").style.display != "none"){
                   showDirectionsUserMessage("localinfo");
                   e.target.checked = false;
             }else{
                updateHashValueInUrl(localinfoTag,"wikipedia",true);
          }
        }
    } else {
        if(IsMapVisible())  {
            clearLocalInformationOverlays(e.target.id.replace(/show_/, ''));
            updateHashValueInUrl(localinfoTag,'',false);
        }else {
             if(currentPageName.toLowerCase().indexOf("directions")>-1  && document.getElementById("listingContainer").style.display != "none"){
                   showDirectionsUserMessage("localinfo");
                   e.target.checked = true;
             }else{
                updateHashValueInUrl(localinfoTag,"wikipedia",false);
            }
        }
    }
  
}

/* Method used to dispplay the local information */
function showLocalInformation(key) {
  if(IsMapVisible() && CheckZoomFactor()== true) {   
    clearLocalInformationOverlays(key);
    document.getElementById('show_'+key).disabled=true;
    IsWikipediaResultsLoaded = false;
    showMap(true);
    loadingStatus(true);
    localSearcher = MMFactory.createSearchRequester(overlayLocalInformationCallback);
    search = new MMSearch();
    search.bounding_box = mapviewer.getMapBounds();
    search.point = mapviewer.getCurrentPosition();
    search.data_source = localInformationOverlayKeys[key].dataSource;
    search.count = 100;
    localSearcher.search(search);
    return false; 
  }  
}

/* Function used to clear the local information overlay */
function clearLocalInformationOverlays(key) {
 var results = localInformationOverlayKeys[key].results;
    if (results) {
      var totalRecords = results.length;
        for (var i = 0; i < totalRecords ; i++) {
            mapviewer.removeOverlay(results[i]);
        }
    }//end of if 
}

/* Callback method the POI's search */
function overlayLocalInformationCallback(results) {
    //check for the error
    if (localSearcher.error_code || results[0].error) {
       IsWikipediaResultsLoaded = true;
        loadingStatus(false);
        return;
    }
    var key = "wikipedia";
    newResults = [];
    if (results[0].total_record_count > 0) {
        var createPoiHtml = getPoiHtml;
        for (var i = 0, l = results[0].records.length; i < l; ++i) {
            var record = results[0].records[i];
            if (record) {
             var html = createPoiHtml(record, key);
             var point = record.point;
             var marker = mapviewer.createMarker(point, { 'icon': localInformationOverlayKeys[key].icon });
             marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'wikipediaInfobox' });
             newResults.push(marker);
            } //end of record
        } //end of for loop
    } //end  of if

    localInformationOverlayKeys[key].results = newResults;
    IsWikipediaResultsLoaded = true;
    loadingStatus(false);
}

/* Method used for showing the loading status for the amenities and local information */
function loadingAmenitiesStatus(bool) {
    poiLoaderId.style.display = bool ? 'block' : 'none';
}

/* Method used for the getting the html for the POI's */
function getPoiHtml(record, key) {
    // create a StringBuilder class instance
    var html = new StringBuilder();
    key = key.toLowerCase();
    if (key == "hospitals" || key == "gyms" || key == "parking" || key == "underground" || key == "railwaystations" 
             || key == "publictransport" || key == "cinemas" || key == "libraries" || key == "localshops" 
             || key == "pubs") {
             
        html.append("<div  class='popupContentDiv'>");
        html.append("<div class='popupHeader'>");
        html.append("<div class='MMleftArrow'></div>");
        html.append("<div class='popup_title_schools'>" + record.Name + "</div>");
        html.append("</div><div class='popupContent'>");
          
        var address_amenities = "";
        if (checkIsNullOrEmpty(record.street)) {
            address_amenities += record.street + ", ";
        }

        if (checkIsNullOrEmpty(record.town)) {
            address_amenities += record.town + ", ";
        }

        if (checkIsNullOrEmpty(record.pc)) {
            address_amenities += record.pc;
        }
        if (address_amenities != "") {
            html.append("<div class='marginbottom address'><span class='popup_subtitle'>Address: </span>");
            html.append(address_amenities);
            html.append("</div>");
        }

        if (checkIsNullOrEmpty(record.Telnum)) {
            html.append("<div class='marginbottom'><span class='popup_subtitle'>Telephone: </span>" 
                + record.Telnum + "</div>");
        }

        if (checkIsNullOrEmpty(record.Http)) {
            if (record.Http.substring(0, 7) != 'http://') {
                record.Http = 'http://' + record.Http;
            }

            html.append("<div class='marginbottom'><span class='popup_subtitle'>Website: </span>"
                 +" <a target='_blank' href='" 
                 + record.Http + "' >" + record.Http + "</a></div>");
        }
        if(address_amenities != ""){
         html.append(" <div> get directions to <a class='cursorstyle' title='Click here to get directions' onclick=\"GoToDirectionsFromThere('"+address_amenities
          +"')\" > here</a> or <a class='cursorstyle' title='Click here to get directions' onclick=\"GoToDirectionsFromHere('"
           +address_amenities+"')\" >from here</a></div>");
       } 
    } else if (key == "wikipedia") {
        html.append("<div  class='popupContentDiv_wikipedia'>");
        html.append("<div class='popupHeader'>");
        html.append("<div class='MMleftArrow'></div>");
        html.append("<div class='popup_title_schools'>" + record.title + "</div>");
        html.append("</div><div class='popupContent'>");
        html.append("<div class='wikipediaimgdiv'>");
        if (checkIsNullOrEmpty(record.img_url)) {
            html.append("<img  class='imgwikipedia' height='" + record.img_height + "' width='" 
                  + record.img_width + "' src='" + record.img_url + "'  alt='wikipedia image' /> ");
        }

        html.append("<div>");

        if (checkIsNullOrEmpty(record.intro)) {
            html.append(record.intro);
        }

        html.append("</div>");
        html.append("</div>");
    }
    
   //check if the record is of search by lat lon 
   //and require back button to go back to property details page 
   if(isBackButtonRequired){
     if (checkIsNullOrEmpty(searchType) && searchType == 6) {
      html.append("<div class='popupbackbuttondiv'>"
           +"<input type='button' id='btnBack' onclick=\"RedirectToReferrerPage();\" "
           +"class='button_back' value='Back to property details' /></div>");
        }
   }  
    html.append("</div></div>"); //end of main outer div
    return html.toString();
}

/* Function used to clear the overlays for amentities and local information */
function clearAmentitiesOverlay() {
    removeLocalInfoOverlay();

    // Rest the overlays result set
    for (var key in overlays) {
        overlays[key].results = null;
    }
}

/* Remove the amenities and local information overlay */
function removeLocalInfoOverlay() {
    // Remove all the current overlays as we will be display a new set
    for (var key in overlays) {
        var results = overlays[key].results;
        if (results) {
            for ( var i = 0, l = results.length; i < l; ++i) {
                if (results[i]) {
                    mapviewer.removeOverlay(results[i]);
                }
            } //end of the inner for loop   
        } //end of the if statement
    } //end of the outer for loop
}

/* Method used to display the pois based on key*/
function displayOverlays(key) {
    if(IsMapVisible() == true && CheckZoomFactor() == true) {
        showMap(true);
        IsMultimapAmenitiesResultsLoaded = false;
        loadingStatus(true);
        loadingAmenitiesStatus(true);
        currentKey = key;
        var results = overlays[key].results;

        if (results) {
            var totalPoisCount = results.length;
            for (var i = 0; i < totalPoisCount; ++i) {
                mapviewer.redisplayOverlay(results[i]);
            }
        }

        localSearcher = MMFactory.createSearchRequester(overlayCallback);
        search = new MMSearch();
        search.bounding_box = mapviewer.getMapBounds();
        search.point = mapviewer.getCurrentPosition();
        search.data_source = overlays[key].dataSource;
        search.count = 100;
        localSearcher.search(search);
        return false;
    }  
}

/* Callback method the POI's search */
function overlayCallback(results) {
    //check for the error
    if (localSearcher.error_code || results[0].error) {
       IsMultimapAmenitiesResultsLoaded = true;
        loadingAmenitiesStatus(false);
        loadingStatus(false);
        return;
    }
    for (var key in overlays) {
        if (overlays[key].dataSource == results[0].dataSource) {
            currentKey = key;
            break;
        }
    }
    key = currentKey;
    var chkStatus = document.getElementById('show_' + key).checked;
    if (!chkStatus) {
        return;
    }
    var allResults = overlays[key].results;
    if (!allResults) {
        allResults = [];
        overlays[key].results = allResults;
    }

    // Don't add the new results to allResults as we go
    // as it'll slow down each batch (we'll end up checking the entry
    // that we just added).
    newResults = [];
    if (results[0].total_record_count > 0) {
             
       var createPoiHtml = getPoiHtml;
        for (var i = 0, l = results[0].records.length; i < l; ++i) {
            var record = results[0].records[i];
            if (record) {
                var found = false;
                for (var j = 0, l2 = allResults.length; j < l2; ++j) {
                    if (allResults[j].dbid == record.id) {
                        found = true;
                    }
                }
                if (!found) {
                    var html = createPoiHtml(record, key);
                    var point = record.point;
                    var marker = mapviewer.createMarker(point, { 'icon': overlays[key].icon });

                    if (key != "wikipedia") {
                        marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox' });
                    }
                    else {
                        //marker.setInfoBoxContent(html);
                        marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'wikipediaInfobox' });
                    }

                    marker.dbid = record.id;
                    newResults.push(marker);

                } //end of found
            } //end of record
        } //end of for loop
    } //end  of if

    overlays[key].results = allResults.concat(newResults);
    IsMultimapAmenitiesResultsLoaded = true;
    loadingAmenitiesStatus(false);
    loadingStatus(false);
}

/* Function used for creating the marker */
function createMarker(loc, html, num) {
    var marker = mapviewer.createMarker(loc, { 'icon': imgProperty });
    marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'altinfobox' });
    return marker;
}

/* Function used for searching the checked amenities and local information  */
function displayCheckedAmenities() {
if(CheckZoomFactor()) {
    clearAmentitiesOverlay();
    var dataSource = '';
    for (var key in overlays) {
        var el = document.getElementById('show_' + key);
        if (el) {
            if (el.checked) {
                dataSource += overlays[key].dataSource + ','
            }
        }
    } //end of the for loop
 
    if (dataSource != '') {
        showMap(true);
        dataSource = dataSource.substring(0, dataSource.length - 1);
        searcherAmenities = MMFactory.createSearchRequester(localInfoCallback);
        search = new MMSearch();
        search.point = mapviewer.getCurrentPosition();
        search.bounding_box = mapviewer.getMapBounds();
        search.data_source = dataSource;
        search.count = 500;
        IsMultimapAmenitiesResultsLoaded = false;
        loadingStatus(true);
        loadingAmenitiesStatus(true);
        searcherAmenities.search(search);
    }
  }  
  return false;
}

/* Amenities and local information search call back function  */
function localInfoCallback(results) {
    if (searcherAmenities.error_code || results[0].error) {
       IsMultimapAmenitiesResultsLoaded = true;
        loadingAmenitiesStatus(false);
        loadingStatus(false);
        return;
    }
    if (searcherAmenities.record_sets != null) {
        for (var count = 0, l = searcherAmenities.record_sets.length; count < l; count++) {
        if (searcherAmenities.record_sets[count].records) {
            for (var key in overlays) {
                if (overlays[key].dataSource == searcherAmenities.record_sets[count].dataSource) {
                    currentKey = key;
                    break;
                }
            } //end of the for loop
            newResults = [];
            key = currentKey;
            var createPoiHtml = getPoiHtml;
            for (var record_count = 0, rl = searcherAmenities.record_sets[count].records.length; record_count < rl; record_count++) {
            var record = searcherAmenities.record_sets[count].records[record_count];
            if (record) {
                var html = createPoiHtml(record, key);
                var point = record.point;
                var marker = mapviewer.createMarker(point, { 'icon': overlays[key].icon });
                if (key != "wikipedia") {
                    marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox' });
                } else {
                   marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'wikipediaInfobox' });
                }
                newResults.push(marker);
            } //end of record
            } //end of the for loop

            overlays[key].results = newResults;
            } //end of the if condition   
        } //end of the outer for loop
    } //end of the if statement
    
    IsMultimapAmenitiesResultsLoaded = true;
    loadingAmenitiesStatus(false);
    loadingStatus(false);
}


/* Function used for searching the checked amenities and local information  */
function searchLocalInformationWithinMapBounds () {
 if(chkWikipedia.checked == false) {
    return;
 }
 if(CheckZoomFactor()) {
  var key = "wikipedia";
  clearLocalInformationOverlays(key);
  var dataSource=localInformationOverlayKeys[key].dataSource;
  localSearcher = MMFactory.createSearchRequester(overlayLocalInformationCallback);
  search = new MMSearch();
  search.point = mapviewer.getCurrentPosition();
  search.bounding_box = mapviewer.getMapBounds();
  search.data_source = dataSource;
  search.count = 100;
  IsWikipediaResultsLoaded = false;
  showMap(true);
  loadingStatus(true);
  localSearcher.search(search);
  return false;
 }  
}

/*************** Business Results under the local amenities navigation ****/

/* Method used to clear the business results form the map and array */
function clearVEOverlays() {
    var totalRecords = BusinessDirectoryResults.length; 
    if(totalRecords > 0) {
        for ( var i = 0; i < totalRecords; i++) {
         if (BusinessDirectoryResults[i]) {
                mapviewer.removeOverlay(BusinessDirectoryResults[i]);
            }
        }
    }
}

/* Method used to setting the visibility of the pager navigation headings */
function SetPagerLinksVisibility(bool) {
   document.getElementById("pager").style.display = bool ? "block" : "none";
}

/*  Method used to clear amenities*/
function clearVEAmenitiesOverlays() {
    for (var key in VEOverlayKeys) {
       hideVEOverlays(key);
    }
}

/* Method used to create the html for the amenities pop up */
function createLocalAmenitiesMarkers(record) {
    // create a StringBuilder class instance
    var html = new StringBuilder();
    html.append("<div  class='popupContentDiv'>");
    html.append("<div class='popupHeader'>");
    html.append("<div class='MMleftArrow'></div>");
    html.append("<div class='popup_title_schools'>" + record.Name + "</div>");
    html.append("</div><div class='popupContent'>");
    
    if (checkIsNullOrEmpty(record.Address)) {
        html.append("<div class='marginbottom address'><span class='popup_subtitle'>Address: </span>");
        html.append(record.Address);
        html.append("</div>");
    }
    if (checkIsNullOrEmpty(record.PhoneNumber)) {
        html.append("<div class='marginbottom'><span class='popup_subtitle'>Telephone: </span>" + record.PhoneNumber 
                   + "</div>");
    }
    if (checkIsNullOrEmpty(record.Website)) {
         html.append("<div class='marginbottom'><span class='popup_subtitle'>Website: </span>"
         +" <a target='_blank' href='" 
         + record.Website + "' >" + record.Website + "</a></div>");
        }
        
          html.append(" <div> get directions to <a class='cursorstyle' title='Click here to get directions' onclick=\"GoToDirectionsFromThere('"+record.Address
       +"')\" > here</a> or <a class='cursorstyle' title='Click here to get directions' onclick=\"GoToDirectionsFromHere('"
       +record.Address+"')\" >from here</a></div>");
     
    //check if the record is of search by lat lon 
    //and require back button to go back to property details page 
    if(isBackButtonRequired) {
     if (checkIsNullOrEmpty(searchType) && searchType == 6) {
           html.append("<div class='popupbackbuttondiv'>"
           +"<input type='button' id='btnBack' onclick=\"RedirectToReferrerPage();\" "
           +"class='button_back' value='Back to property details' /></div>");
        }
    }  
    html.append("</div></div>"); //end of main outer div
    return html.toString();
}

/* Method used to handle the clustering of Business Results */
function handleClusteringForVEMarkers(groupName) {
    mapviewer.declutterGroup( groupName, {}, MM_DECLUTTER_GRID ); 
    return false;
}


/* Method used to search the business results based on the free search text */
function searchBusinessResultsWithVE() {
    disableBusinesSearchButton(true);   
    IsBusinessResultsLoaded = false;
    clearVEOverlays();
    handleClusteringForVEMarkers('business');
    var query = '';
    //check for first time records are loaded
    // or with paging

    if(TxtLocalSearchCategory.value != "" && TxtLocalSearchCategory.value != AmenitiesDefaultSearhText)  {
       query = unescape(TxtLocalSearchCategory.value)
     }
    if(query.length > 30) {
       query =  query.substring(0,30);
    }

    if(CurrentRecordIndex == 0) {
        SetPagerLinksVisibility(true);
        pager.style.display="block";
        pagerLinks.style.display="block";
        pager.innerHTML ="Results for <strong>"+ query +"</strong> around <strong>"
                         +  searchLocation +"</strong>";
    }  
    IsBusinessResultsLoaded = false;
    loadingStatus(true);
    var qStringValues = "";
    qStringValues = "query="+ query +"&location="+searchLocation+"&record_index="
                  + CurrentRecordIndex +"&search=2";
    var ajaxRequest = new ajaxObject(VEServerScriptPageUrl);
    BusinessDirectoryResults = [];
    ajaxRequest.callback = function(JsonString)  {
        if (checkIsNullOrEmpty(JsonString))  {
         try {
            var results = eval('(' + JsonString + ')');
            var totalResults = results.BusinessResult.length;
            if(CurrentRecordIndex == 0) {
                 TotalEstimatedMatches = results.Total[0].Count;
            } 
            
            //add the pointer reference for the performance tuning
            var createBusinessSearchMarkers = createLocalAmenitiesMarkers;
            for(var i=0;i < totalResults; i++) {
            var html = createBusinessSearchMarkers(results.BusinessResult[i])
            var point = new MMLocation(new MMLatLon(results.BusinessResult[i].Lat,results.BusinessResult[i].Lon));
            var icon = MM_DEFAULT_ICON.copy();
            icon.groupName  = 'business';
            var marker = mapviewer.createMarker(point, { 'icon' : icon,'text': (i+1+CurrentRecordIndex) });
            marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox popupInfobox_business' });
            BusinessDirectoryResults.push(marker);
            }
           
            if(BusinessDirectoryResults.length > 0 ) {
              mapviewer.goToPosition(mapviewer.getAutoScaleLocation(BusinessDirectoryResults));
            }

         }catch(err){} 
    }
    
    ShowPagerLinks(CurrentRecordIndex,TotalEstimatedMatches);
    IsBusinessResultsLoaded = true;
    loadingStatus(false);
    disableBusinesSearchButton(false);
    }
    
    ajaxRequest.update(qStringValues); 
}

/* Method used to show the Pager links based on the current index
   and the no of records
*/
function ShowPagerLinks(Index,TotalRecords) {
    var lastRecordSizeIndex = TotalRecords -25 ;
    if(Index == 0) {
     if(TotalEstimatedMatches < 25) {
        pagerLinks.innerHTML ="Nearest <strong>"+ TotalEstimatedMatches +"</strong> of <strong>"
          + TotalEstimatedMatches +"</strong>" ;
     } else {
      pagerLinks.innerHTML ="Nearest <strong>25</strong> of <strong>"+ TotalEstimatedMatches +"</strong> <a href='#' title='Next' onclick ='ShowNextRecords()'>next 25 »</a>";
     }
    } else {
     if(CurrentRecordIndex >=lastRecordSizeIndex) {
        pagerLinks.innerHTML ="<strong>"+ CurrentRecordIndex+"–"+ TotalRecords +"</strong> of <strong>"+ TotalEstimatedMatches +"</strong> <a href='#' onclick='ShowPreviousRecords()'>  « prev 25 </a> ";
     } else {
         pagerLinks.innerHTML ="<strong>"+ CurrentRecordIndex+"–"+ (CurrentRecordIndex + 25) +"</strong> of <strong>"+ TotalEstimatedMatches +"</strong> <a href='#' title='Previous' onclick='ShowPreviousRecords()'>  « prev 25 </a> | <a href='#' onclick='ShowNextRecords()' title='Next' > next 25 » </a>";
      }
    }
}

/* Method used to get the next 25 records from the 
   the pagination links
 */
function ShowNextRecords() {
    CurrentRecordIndex += 25;
    searchBusinessResultsWithVE();
}

/* Method used to get the previous 25 records from the 
   the pagination links
 */
function ShowPreviousRecords() {
    CurrentRecordIndex -= 25;
    searchBusinessResultsWithVE();
}

/* Method used to hide the pop up */
function hideConstituencyPopup() { 
    if(document.getElementById("popup") != null){
        document.getElementById("popup").className = "hide";
    }
    if(document.getElementById("popupdetails") != null){
        document.getElementById("popupdetails").innerHTML = "";
    }
}

/*Method used to hide the property finder logo */
function showShootHillLogo() {
    if(currentPageName.toLowerCase().indexOf("map") > -1){
        if(isCurrentlyShootHillDataDisplaying()) {
           shootHillLogo.style.display = "block" ;
           propertyFinderLogo.style.display = "none";
         } else {
           if(checkIsNullOrEmpty(searchType)) {
              shootHillLogo.style.display = "none" ;
              propertyFinderLogo.style.display = "none";
           } else {
              shootHillLogo.style.display = "none" ;
              propertyFinderLogo.style.display = "block";
           }
        }
    }
}

/* Method used to check whether shoot hill data is currently displaying or not */
function  isCurrentlyShootHillDataDisplaying() {
  if(document.getElementById("show_crime").checked) {
    return true;
  } 
  if(document.getElementById("show_constituencies").checked) {
    return true;
  } 
  return false;
}

/* Method used for show the constituency details on radio button checked */    
function displayConstituencyOverlay(key) {
if(IsMapVisible()) {

 currentOverlay = key;
   // check if the option is clicked again and again for the same bundaries
   // or not
  if(previousOverlayKey != key || isMapChanged == true) {
     switch(key) {
       case "none" : {
          showOverlayMsg(1,false);
          clearLocalInfoOverlay();
          break;
        }    
        case "constituencies" : {
            showOverlayMsg(2,true);
            clearCrimeCustomOverlay();
            if(currentHeatMap != null){
                clearHeatmapOverlays();
            }
            searchCrimeDataWithinMapBounds();            
            break;
        }  
        case "crime" : {
           showOverlayMsg(1,true);
           clearConstituencyOverlay();
          if(currentHeatMap != null){
                clearHeatmapOverlays();
            }
           searchCrimeDataWithinMapBounds();
           break;     
        }   
     }
   }  
   
  previousOverlayKey = key; 
  isMapChanged = false;  
 }    
}

/* This method is used for showing the message for the use to see the crime and constituency
   details for the crime and constituency overlays
*/
function showOverlayMsg(intValue,bool) {
 if(IsMapVisible()) {
     //// intValue = 1 for crime 
     ////  intValue = 2 for constituency
     if(bool ) {  
         overlayMsg.style.display="block";
         switch(intValue) {
          case 1:
            overlayMsg.innerHTML="Click on the map for detailed information on crime data";
            break;
          case 2:   
            overlayMsg.innerHTML="Click on the map to get constituency, primary care and socio-economic data";
            break;
         }
      }  else  {
        overlayMsg.style.display="none";
      }   
  }  
}

/* Method used to remove the heat map overlay for crime */
function clearLocalInfoOverlay() {
      hideConstituencyPopup();
      mapviewer.removeOverlay(crimeNewLayer);
      mapviewer.removeOverlay(constituencyNewLayer);
}
 
/* Method used to remove the heat map overlay for crime */
function clearCrimeCustomOverlay() {
      mapviewer.removeOverlay(crimeNewLayer);
}
 
/* Method used to remove the heat map overlay for crime */
function clearConstituencyOverlay() {
      mapviewer.removeOverlay(constituencyNewLayer);
}
 
/* Method used to search the crime data within map boundaries*/ 
function searchCrimeDataWithinMapBounds() {
  if( currentOverlay == "crime") {
      mapviewer.addOverlay(crimeNewLayer);
      if(version < 7) {
          window.tile = new IETileLayerFix( mapviewer, 'MMTileLayerOverlay1' );
      }
   } else  {
        mapviewer.addOverlay(constituencyNewLayer);
   }    
  
}
 
 /* This method is used to add the custom tiles overlay */ 
function addCustomTilesOverlay() {
   l_copyright = new MMCopyright(1,[new MMBounds(new MMLatLon(-90, -180),new MMLatLon(90, 180))],0,"©2009 local.uk.msn.com");
   l_copyrightCollection = new MMCopyrightCollection('MSN Local - ');
   l_copyrightCollection.addCopyright(l_copyright);
   
   window.crimetilelayers = new MMTileLayer(l_copyrightCollection ,7, 18);
   crimetilelayers.isPng = function(){return true;};
   crimetilelayers.getOpacity=function() {return 0;};
   crimetilelayers.getTileUrl = getCrimeTileUrl;
   crimeNewLayer = new MMTileLayerOverlay(crimetilelayers);
   
   window.constituencytilelayers = new MMTileLayer(l_copyrightCollection ,7, 18);
   constituencytilelayers.isPng = function(){return true;};
   constituencytilelayers.getOpacity=function() {return 0.5;};
   constituencytilelayers.getTileUrl = getConstituencyTileUrl;
   constituencyNewLayer = new MMTileLayerOverlay(constituencytilelayers);
      
  l_tilelayers = new MMTileLayer(l_copyrightCollection ,7, 18);
  l_tilelayers.isPng = function(){return true;};
  l_tilelayers.getOpacity=function() {return 0;};
  l_tilelayers.getTileUrl = l_CustomGetTileUrl;
  newlayer_pricesandtrends = new MMTileLayerOverlay(l_tilelayers);
    
  //fallers heat map overlays
  risersTileLayers = new MMTileLayer(l_copyrightCollection ,7, 18);
  risersTileLayers.isPng = function(){return true;};
  risersTileLayers.getOpacity=function() {return 0;};
  risersTileLayers.getTileUrl = getRisersHeatImgTileUrl;
  newlayer_pricefallers = new MMTileLayerOverlay(risersTileLayers);
 }
 
/* Method used to get the crime images path */
function getCrimeTileUrl(l_a,l_b) {
     return CrimeDataLocation +'r' + getQuadKey(l_a.x, l_a.y, l_b-1) + '.png';
}

/* Method used to get the constituency images path */
function getConstituencyTileUrl(l_a,l_b) {
  return  ConstituencyHeatMapImages +'r' + getQuadKey(l_a.x, l_a.y, l_b-1) + '.png';
}

 /* Method used for  getting the corresponding quadrant image for overlaying */
function l_CustomGetTileUrl(l_a,l_b) {
 var url ;
 switch(currentHeatMap) {
   case 'RisesAndFallers':
     url = FallersOnHeatMapImages +'r' + getQuadKey(l_a.x, l_a.y, l_b-1) + '.png';
     break;
   case 'RentalYeilds':
     url = RentalYeildHeatMapImages +'r' + getQuadKey(l_a.x, l_a.y, l_b-1) + '.png';
     break;
   case 'AveragePrices':
     url = AveragePricesHeatMapImages +'r' + getQuadKey(l_a.x, l_a.y, l_b-1) + '.png';
     break;    
   
 }
 return url;
}

/* Method used for  getting the corresponding quadrant image for overlaying */
function getRisersHeatImgTileUrl(l_a,l_b) {
 var url = RisesOnHeatMapImages +'r' + getQuadKey(l_a.x, l_a.y, l_b-1) + '.png';
 return url;
}

/* This is used to get the tile url complete path */
function getQuadKey(tileX,tileY,zoom) {
    var quadKey = "";
    for (var i = zoom; i > 0; i--) {
        var digit = '0';
        var mask = 1 << (i - 1);
        if ((tileX & mask) != 0) {
            digit++;
        }
        if ((tileY & mask) != 0) {
            digit++;
            digit++;
        }
        quadKey += digit;
    }
    return quadKey;
}

/* This is used to add the layers for the custom tiles for
   IE6 and below browsers
*/
function IETileLayerFix( mapviewer, tile_layer ) {
    tile_layer = (tile_layer ? tile_layer : 'MMTileLayerOverlay1');
    this.TILE_LAYER = mapviewer.layers[tile_layer];
    var me = this;
    this.TILE_LAYER_DIV = (function() {
        if (me.TILE_LAYER.images && me.TILE_LAYER.images[0][0])
            return me.TILE_LAYER.images[0][0].parentNode;
    });

    this.applied = [];
    var me = this;
    mapviewer.addEventHandler( 'changeZoom', function() {
        var tile_layer = me.TILE_LAYER_DIV();
        if (tile_layer) {
            tile_layer.display_state = tile_layer.style.display;
            tile_layer.style.display = 'none';
        }
    } );

    mapviewer.addEventHandler( 'tilesLoaded', function() {
        me._remove();
        me._apply();

        var tile_layer = me.TILE_LAYER_DIV();
        if (tile_layer)
            tile_layer.style.display = tile_layer.display_state;
    } );

    mapviewer.handleEvent( 'changeZoom' );
}

IETileLayerFix.prototype._remove = function() {
    for (var i = 0, j = this.applied.length; i < j; i++) {
        this.applied[i].img.style.display = this.applied[i].img.display_state;

        var div = this.applied[i].div;
        if (div && div.parentNode)
            div.parentNode.removeChild( div );
    }

    this.applied = [];
}

IETileLayerFix.prototype._apply = function() {
    var images = this.TILE_LAYER_DIV().getElementsByTagName( 'img' );

    for (var i = 0, j = this.TILE_LAYER.images.length; i < j; i++) {
        for (var k = 0, l = this.TILE_LAYER.images[i].length; k < l; k++) {
            var image = this.TILE_LAYER.images[i][k];
            if (image.getAttribute( 'src' )) {
                var before = image.style.getAttribute( 'cssText' );
                var filter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=';
                filter = '; ' + filter + '\'' + image.getAttribute( 'src' ) + '\', sizingMethod=\'scale\');';

                var div = document.createElement( 'div' );
                div.style.setAttribute( 'cssText', before + filter );

                image.display_state = image.style.display;
                image.style.display = 'none';
                image.parentNode.appendChild( div );

                var applied = { 'img' : image, 'div' : div, 'filter' : filter };
                this.applied[this.applied.length] = applied;
            }
        }
    }
}

/* Method used to display the amenities using virtual earth webservice 
   on individual option clicked
*/
function showVEOverlays(key) {
 if(IsMapVisible()) {
    IsVEAmenitiesResultLoaded = false;
    loadingStatus(true);
    var latlon =  mapviewer.getCurrentPosition();
    handleClusteringForVEMarkers(VEOverlayKeys[key].groupName);
    var url = VEServerScriptPageUrl;
    var qStringValues = "amenities="+ key +"&location="+ searchLocation 
                      +"&latitude="+ latlon.lat  +"&longitude="+ latlon.lon  +"&search=3";
    var ajaxRequest = new ajaxObject(url);
    var markers = [];
    ajaxRequest.callback = function(JsonString)  {
        if (checkIsNullOrEmpty(JsonString))  {
           try {
                var results = eval('(' + JsonString + ')');
                var totalResults = results.BusinessResult.length;
                //add the pointer reference for the performance tuning
                var createBusinessSearchMarkers = createLocalAmenitiesMarkers;
                for(var i=0;i < totalResults; i++) {
                    var html = createBusinessSearchMarkers(results.BusinessResult[i])
                    var point = new MMLocation(new MMLatLon(results.BusinessResult[i].Lat,results.BusinessResult[i].Lon));
                    var marker = mapviewer.createMarker(point, { 'icon': VEOverlayKeys[key].icon });
                    marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox' });
                    markers.push(marker);
                }
                if(markers.length>0) {
                   VEOverlayKeys[key].results = markers;
                }
               
           }catch(err){} 
        }
        
        IsVEAmenitiesResultLoaded = true;
        loadingStatus(false);
    }
    
  ajaxRequest.update(qStringValues); 
 } 
}

/* Method used to search the amenities with virtaul earth 
   web services
*/
function SearchVEAmenitiesWithinMapbounds() {
    var amenitiesOptions  = '';
     //search for virtual earth pois
     for (var key in VEOverlayKeys) {
        var el = document.getElementById('show_' + key);
        if (el) {
            if (el.checked) {
                amenitiesOptions += key +'|';
                handleClusteringForVEMarkers(VEOverlayKeys[key].groupName);
            }
        }
    }  
    if(amenitiesOptions != '')    {
        clearVEAmenitiesOverlays();
        amenitiesOptions =  amenitiesOptions.substring(0,amenitiesOptions.length-1);
        IsVEAmenitiesResultLoaded = false;
        loadingStatus(true);
        var latlon =  mapviewer.getCurrentPosition();
        var qStringValues = "amenities="+escape(amenitiesOptions) +"&location="+ searchLocation 
                    +"&latitude="+ latlon.lat  +"&longitude="+ latlon.lon  +"&search=3";
        var ajaxRequest = new ajaxObject(VEServerScriptPageUrl);
        var individualResultSet = { supermarkets: [],pubs: [],localShops: [],cinemas: [],gyms: [] };
        ajaxRequest.callback = function(JsonString)  {
            if (checkIsNullOrEmpty(JsonString))  {
               try {  
                    var results = eval('(' + JsonString + ')');
                    var totalResults = results.BusinessResult.length;
                  
                    //add the pointer reference for the performance tuning
                    var createBusinessSearchMarkers = createLocalAmenitiesMarkers;
                    for(var i=0;i < totalResults; i++) {
                        var html = createBusinessSearchMarkers(results.BusinessResult[i])
                        var point = new MMLocation(new MMLatLon(results.BusinessResult[i].Lat,results.BusinessResult[i].Lon));
                        var key =results.BusinessResult[i].Key;
                        var marker = mapviewer.createMarker(point, { 'icon': VEOverlayKeys[key].icon });
                        marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox' });
                        individualResultSet[key].push(marker);
                    }
                    for (var key in individualResultSet) {
                        VEOverlayKeys[key].results = individualResultSet[key];
                    }
                   
               }catch(err){} 
            }
            IsVEAmenitiesResultLoaded = true;
            loadingStatus(false);
        }
        ajaxRequest.update(qStringValues);  
    } 
        
}

/* Method used to search the business results based on the free search text */
function SearchBusinessResultsWithinMapbounds() {
  disableBusinesSearchButton(true);  
 
  if(TxtLocalSearchCategory.value != "" && TxtLocalSearchCategory.value != AmenitiesDefaultSearhText)  {
    if(pager.style.visibility == "")   {       
        SetPagerLinksVisibility(true);  
        pager.style.display = "block";
        pagerLinks.style.display = "block";
       
    }    
    clearVEOverlays();
    handleClusteringForVEMarkers('business');
    CurrentRecordIndex = 0;
    var latlon =  mapviewer.getCurrentPosition();  
    IsBusinessResultsLoaded = false;
    loadingStatus(true);
    var qStringValues = "";
    qStringValues = "query="+ unescape(TxtLocalSearchCategory.value)+"&location="+searchLocation+"&record_index="
                  + CurrentRecordIndex +"&latitude="+ latlon.lat  +"&longitude="+ latlon.lon  +"&search=4";;
    var newLocation = '';
    var ajaxRequest = new ajaxObject(VEServerScriptPageUrl);
    BusinessDirectoryResults = [];
    ajaxRequest.callback = function(JsonString)  {
        if (checkIsNullOrEmpty(JsonString))  {
         try {
          
            var results = eval('(' + JsonString + ')');
            TotalEstimatedMatches = results.Total[0].Count;
            newLocation = results.NewArea[0].PostalCode;
            var totalResults = results.BusinessResult.length;
            
            //add the pointer reference for the performance tuning
            var createBusinessSearchMarkers = createLocalAmenitiesMarkers;
            for(var i=0;i < totalResults; i++) {
                var html = createBusinessSearchMarkers(results.BusinessResult[i])
                var point = new MMLocation(new MMLatLon(results.BusinessResult[i].Lat,results.BusinessResult[i].Lon));
                var icon = MM_DEFAULT_ICON.copy();
                icon.groupName  = 'business';
                var marker = mapviewer.createMarker(point, { 'icon' : icon,'text': (i+1+CurrentRecordIndex) });
                marker.setInfoBoxContent('<p>' + html + '<' + '/p>', { className: 'popupInfobox popupInfobox_business' });
                BusinessDirectoryResults.push(marker);
            }
           
            if(totalResults == 0) {
               TotalEstimatedMatches = 0;
               CurrentRecordIndex = 0;
            }
          
         }catch(err){TotalEstimatedMatches = 0;CurrentRecordIndex = 0;} 
    } else {
      TotalEstimatedMatches = 0;
      CurrentRecordIndex = 0;
    }
   
    pager.innerHTML ="Results for <strong>"+ unescape(TxtLocalSearchCategory.value) +"</strong> around <strong>"
     +  newLocation +"</strong>"
    ShowPagerLinks(CurrentRecordIndex,TotalEstimatedMatches);
    IsBusinessResultsLoaded = true;
    loadingStatus(false);
    disableBusinesSearchButton(false); 
    }
    
    ajaxRequest.update(qStringValues); 
 }    
}

/* Method used to delete property from favourite list */
function  AddDeletePropertyFromFavourites(listingRkey,AddOrDelete,markerIndex) { 
    loadingStatus(true);
    var queryString = "";
    queryString = window.location.search.substring(1);
    //set the ListingRkey
   if (queryString.indexOf("&ListingRkey") > -1) {
        queryString = replaceQueryString(queryString, "ListingRkey", listingRkey);
    } else if(listingRkey>0) {
        queryString = queryString + "&ListingRkey=" + listingRkey;
    }
    //check the property for addition or deletion    
    if(AddOrDelete == "add") {
     if(queryString.indexOf("&IsDelete")>-1){ 
        queryString =queryString.replace("&IsDelete=1",""); }
        if (queryString.indexOf("&IsAdd") > -1) {
                queryString = replaceQueryString(queryString, "IsAdd", 1);            
        }  else {
                queryString = queryString + "&IsAdd=1"; 
        }
      }
      
    if(AddOrDelete == "delete"){
       if(queryString.indexOf("&IsAdd")>-1) { 
            queryString =queryString.replace("&IsAdd=1",""); 
       }
       if (queryString.indexOf("&IsDelete") > -1) {
            queryString = replaceQueryString(queryString, "IsDelete", 1);                
       } else {
            queryString = queryString + "&IsDelete=1" ;   
       }
    }
    
    if(!dragSearch) {
        queryString = queryString + "&IsMapDrag=0";
    } else {
      //on dragged map, if u add a property to watchlist then no need to add this property to cache,
      // we just need to clear cache
        queryString = queryString + "&IsMapDrag=1";
    }
     if (queryString.indexOf("&IsSame") > -1) {
        queryString = replaceQueryString(queryString, "IsSame", 1)
    }    
    else {queryString = queryString + "&IsSame=1" ; }
     AddORDeletePropertiesFromFavourites(listingRkey,queryString,markerIndex);
}

/* This function is used to get the additional record of property according to page number and page size .*/
function AddORDeletePropertiesFromFavourites(listingRkey,queryString,markerIndex) {
    var xmlHttp;
    var resultReturned;
    try {
        // Firefox, Opera 8.0+, Safari 
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer 
        try { 
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
        } catch (e) {
            try { 
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
            } catch (e) { 
                alert("Your browser does not support AJAX!"); return; 
            }
        }
    }
    
    var markerInfoboxContent = '';
    for(var i = 0; i < propertyMarkers.length; i++){
        if(i == markerIndex){
            markerInfoboxContent = propertyMarkers[i].mmty;
            break;
        }
    }
    // Declare a ready state change event
    xmlHttp.onreadystatechange = function() {
        if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) {
            resultReturned = xmlHttp.responseText;
            if(resultReturned =="False")  { 
              window.location.href = ApplicationPath + "map?" + queryString;
              return;
            }
             if (resultReturned.length > 0) {
                var resultArray = resultReturned.split("$favouritePrptyCount=");        
                var PropertiesCount= parseInt(resultArray[1]);
                resultReturned= resultArray[0];
                document.getElementById('ctl00_ContentPlaceHolder1_uclWatchList1_btnWatchList').value="My Watchlist ("+ PropertiesCount+")"; 
                if(resultReturned == "added") {
                    markerInfoboxContent = markerInfoboxContent.replace
                                            ("<a onkeypress='checkKey(this)'onclick='AddDeletePropertyFromFavourites(" + listingRkey + ", \"add\" ,"+ markerIndex +")' class='watchlistgreen'>Save to watchlist</a>",
                                            "<a onkeypress='checkKey(this)'onclick='AddDeletePropertyFromFavourites(" + listingRkey + ", \"delete\" ,"+ markerIndex +")' class='watchlistred'>Remove from watchlist</a>");
                } else if(resultReturned == "deleted")   {
                     markerInfoboxContent = markerInfoboxContent.replace
                                            ("<a onkeypress='checkKey(this)'onclick='AddDeletePropertyFromFavourites(" + listingRkey + ", \"delete\" ,"+ markerIndex +")' class='watchlistred'>Remove from watchlist</a>",
                                            "<a onkeypress='checkKey(this)'onclick='AddDeletePropertyFromFavourites(" + listingRkey + ", \"add\" ,"+ markerIndex +")' class='watchlistgreen'>Save to watchlist</a>");
                }
               
                if(propertyMarkers[markerIndex]){
                    // for clustered properties
                    if(!propertyMarkers[markerIndex].mmoib) {
                        addPropertiesClusterGroup();
                        propertyMarkers[markerIndex].setInfoBoxContent( markerInfoboxContent, { className: 'altinfobox'});
                        propertyMarkers[markerIndex].openInfoBox();
                    } else {
                        propertyMarkers[markerIndex].setInfoBoxContent( markerInfoboxContent, { className: 'altinfobox'});
                    }
                }
             
             }
        }
        
    loadingStatus(false);
    };
    
   var scriptUrl = FavouritePropScriptPageUrl + "?" + queryString;
   xmlHttp.open("GET", scriptUrl , true);
   xmlHttp.send(null);
}

/* Method used for tracking contact information */
function GetRequestDetails(id, agentId, bedRooms, price, propertyType,loc) {
    var s = s_gi("msnportalukproperty");
    s.prop37 = loc;
    s.prop38 = price;
    s.prop39 = propertyType;
    s.prop40 = bedRooms;
    s.prop36=s.prop37 + "_" + s.prop38 + "_" + s.prop39 + "_" + s.prop40;
    s.linkTrackVars = "prop36,prop37,prop38,prop39,prop40";
    s.tl(this, 'o', 'click to agent');
    if(propertyType=='lease'){
        window.open("http://msn.zoopla.co.uk/to-rent/contact/"+id,"mywindow", "left=150px,top=0px,status=0,toolbar=0,resizable=0,width=390,height=550,scrollbars=1");
        return false;
     } else {
        window.open("http://msn.zoopla.co.uk/for-sale/contact/"+id,"mywindow", "left=150px,top=0px,status=0,toolbar=0,resizable=0,width=390,height=550,scrollbars=1");
        return false; 
     }    
}

/* Method used for redirected to the referrer page for back to property details button */
function RedirectToReferrerPage() {
    if(document.referrer) {
      var referrerUrl = document.referrer;
      var currentPropertyId= getQueryStringValue("Id");
      referrerUrl = replaceQueryString(referrerUrl,"Id",currentPropertyId);
      window.location.href = referrerUrl + window.location.hash;
    
    } else {
        history.go(-1);
    }
    return false;
}

 /* This method is used to show the amenities on the map by lat lon */            
function ShowAmenitiesOnMap(latitude,longitude,propertyId,poiType,type) {
     var temp_url= ApplicationPath +"amenities/map?search=6&type="+type+"&lat="+latitude+"&lon="+longitude+"&Id="+propertyId;
     //update query string hash value
     updateHashValueInUrl("poi",poiType,true);
     window.location.href = temp_url + window.location.hash;
}
/* Method used to redirect to map page to show the school based on school id */
function ShowSchoolOnMap(schoolId,propertyId,schoolType) {
     var temp_url= ApplicationPath +"schools/map?search=6&schoolid="+schoolId+"&Id="+propertyId;
     if(window.location.hash.indexOf('schools=all')== -1) {
        //update query string hash value
        updateHashValueInUrl("schools",schoolType,true);
     }
     window.location.href = temp_url + window.location.hash;
}

/* Redirect to refferer url from intermediate page*/
function RedirectFromIntermediateUrl(url) {
   var time_stamp = new Date();     
    var urlHashValue = window.location.hash;
    if(checkIsNullOrEmpty(urlHashValue)) {
        window.location.href = url+'&time='+ time_stamp.getMilliseconds()+ urlHashValue;
    } else {
        window.location.href = url+'&time='+ time_stamp.getMilliseconds() ;
    }
}
﻿//////////////////////  PropertyDetails.aspx  ////////////////////////////////////
/////////////////////////////////////////////////////////

var mapviewerId = 'dvMapViewer';
//icons used to show on the map for the POI's
var imgProperty = new MMIcon(ImagePath + 'marker.png');
imgProperty.iconSize = new MMDimensions(25, 25);
imgProperty.groupName = 'properties';

function ShowPropertyOnMap(streetAddress, postalCode, city, status) {
 var mapViewerObject = document.getElementById(mapviewerId);  
 try {
    if (!mapViewerObject) {
        return false;
    }
    if (status == 1) {
        MapResize();
    }
    mapViewerObject.value = "";
    mapviewer = MMFactory.createViewer(mapViewerObject);
    mapviewer.setAllowedZoomFactors(4, 18);

    //Add map type widgets
    mapTypeWidget = new MMMapTypeWidget();
    mapviewer.addWidget(mapTypeWidget);
    setMapType();
    //Add map Zoom in out and the pan Widget
    panZoomWidget = new MMPanZoomWidget();
    mapviewer.addWidget(panZoomWidget);
    mapviewer.addEventHandler('endGeocode', endGeocode);
    mapviewer.addEventHandler('changeMapType',changeMapType);
    mapviewer.goToPosition(new MMLocation(new MMAddress({ street: streetAddress, city: city, postal_code: postalCode, country_code: 'GB' }), 11));
    } catch (err) { }
}

/* Function to get the result after geocoding the property address */
function endGeocode(type, target, point, error_code) {
    if (error_code && error_code != 'MM_GEOCODE_MULTIPLE_MATCHES') {
        return;
    }
    if (error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
        return;
    }
    mapviewer.createMarker(point, { 'icon': imgProperty });
}

/* Event handler for the map changed*/
function changeMapType(eventType, eventTarget,oldMapType,newMapType) {
 if(newMapType == 256 || newMapType == 64) {
    mapviewer.setAllowedZoomFactors(19, 20);
 } else {
    mapviewer.setAllowedZoomFactors(4, 18);
 }
}

/* Method used to set the zoom factor based on the map type*/
function setMapType() {
  var mapType = mapviewer.getMapType();
  
  if(mapType == 256 || mapType == 64)   {
      mapviewer.setAllowedZoomFactors(19, 20); 
  } else  {
     mapviewer.setAllowedZoomFactors(4, 18); 
  }
}

/* This is used to resize the map size based on the property description content lenght
   in the property details page
*/
function MapResize() {
    var rightDivHeight = document.getElementById("DetailsRightContent").offsetHeight;
    if (rightDivHeight && rightDivHeight < 323) {
        document.getElementById("mapPreviewer").className = "mapPreviewerClass";
    } else {
        document.getElementById("mapPreviewer").className = "mapPreviewerleftClass";
    }
}

﻿////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////Advertisemt(Used for dap.js (http://ads1.msn.com/library/dap.js)//
////////////////////////////////////////////////////////////////////////////////////////////////////


var _daprr = new Array('http://rad.msn.com/ADSAdClient31.dll?GetSAd=', 'http://a.rad.msn.com/ADSAdClient31.dll?GetSAd=', 'http://b.rad.msn.com/ADSAdClient31.dll?GetSAd='); var _daprs = 0; if (location.hostname.toLowerCase().indexOf('.live.com') != -1)
{ _daprr = new Array('http://rad.live.com/ADSAdClient31.dll?GetSAd=', 'http://a.rad.live.com/ADSAdClient31.dll?GetSAd=', 'http://b.rad.live.com/ADSAdClient31.dll?GetSAd='); }
var _daplp = 'http://ads1.msn.com/library'; var acbMinWdth = 160; var acbAdBarH = 22; var acbDwnLdSt = false; var DPJS_BSC = 0; var DPJS_ACB = 1; var DPJS_4TH = 2; var DPJS_ADV = 4; function dap(qs, fw, fh, ob) {
    var rs = _daprr[_daprs++]; if (_daprs >= _daprr.length) _daprs = 0; var dapIfs = ""; if (typeof (ob) != 'undefined') {
        ob = true; if (rs.length > 0)
        { rs += '&DPJS=' + (DPJS_BSC + DPJS_4TH); }
    }
    else {
        ob = false; if (rs.length > 0)
        { rs += '&DPJS=' + DPJS_BSC; }
    }
    if (_dapUtils.is_ie5up && _dapUtils.is_win && !ob)
    { dapIfs = 'dapIf' + (parseInt(parent.frames.length) + 1); document.write('<iframe id="' + dapIfs + '" src="about:blank" width="' + fw + '" height="' + fh + '" frameborder="0" scrolling="no"></iframe>'); document.frames[dapIfs].document.open("text/html", "replace"); document.frames[dapIfs].document.write('<html><head><title>Advertisement</title></head><body id="' + dapIfs + '" leftmargin="0" topmargin="0"><scr' + 'ipt type="text/javascript">var inDapIF=true;</scr' + 'ipt><scr' + 'ipt type="text/javascript" src="' + rs + qs + '" onreadystatechange="startTimer();"></scr' + 'ipt><scr' + 'ipt type="text/javascript">function startTimer(){if (event.srcElement.readyState == "complete") {window.setTimeout("document.close();", 2000);}}</scr' + 'ipt></body></html>'); }
    else
    { document.write('<scr' + 'ipt src="' + rs + qs + '" type="text/javascript" language="JavaScript"></scr' + 'ipt>'); }
}
function verifyDapResize(idx) {
    if (!adCont[idx].resizeCalled && adCont[idx].acbObj.enabled)
    { dap_Resize(adCont[idx].ifrmid, adCont[idx].w, adCont[idx].h); }
}
function dap_Resize(fid, fw, fh) {
    document.getElementById(fid).width = fw; document.getElementById(fid).height = fh; if (fw > 0 && fh > 0)
    { acbAdResize(fid, fw, fh); }
}
function dapOAF(qs, oa, fw, fh)
{ dap(qs, fw, fh); }
_dapUtilClass = function() {
    var ua = navigator.userAgent.toLowerCase(); var av = navigator.appVersion.toLowerCase(); this.minorVer = parseFloat(av); this.majorVer = parseInt(this.minorVer); this.is_opera = (ua.indexOf("opera") != -1); this.is_mac = (ua.indexOf("mac") != -1); this.is_ff = (ua.indexOf("firefox") != -1); var iePos = av.indexOf('msie'); if (iePos != -1) {
        if (this.is_mac)
        { var iePos = ua.indexOf('msie'); this.minorVer = parseFloat(ua.substring(iePos + 5, ua.indexOf(';', iePos))); }
        else
        { this.minorVer = parseFloat(av.substring(iePos + 5, av.indexOf(';', iePos))); }
        this.majorVer = parseInt(this.minorVer);
    }
    this.is_ie = ((iePos != -1) && (!this.is_opera)); this.is_ie3 = (this.is_ie && (this.majorVer < 4)); this.is_ie4 = (this.is_ie && this.majorVer == 4); this.is_ie4up = (this.is_ie && this.minorVer >= 4); this.is_ie5 = (this.is_ie && this.majorVer == 5); this.is_ie5up = (this.is_ie && this.minorVer >= 5); this.is_ie5_5 = (this.is_ie && (ua.indexOf("msie 5.5") != -1)); this.is_ie5_5up = (this.is_ie && this.minorVer >= 5.5); this.is_ie6 = (this.is_ie && this.majorVer == 6); this.is_ie6up = (this.is_ie && this.minorVer >= 6); this.is_webtv = (ua.indexOf("webtv") != -1); this.is_msn = (av.indexOf("msn") >= 0); this.is_win = ((ua.indexOf("win") != -1) || (ua.indexOf("16bit") != -1)); this.is_mac = (ua.indexOf("mac") != -1); if (this.is_mac) { this.is_win = !this.is_mac; }
    if (this.is_ff) {
        this.ffPos = ua.indexOf("firefox"); if (ua.length > this.ffPos + 8)
        { this.majorVer = parseInt(ua.substring(this.ffPos + 8)); }
        if (ua.length > this.ffPos + 10)
        { this.minorVer = parseInt(ua.substring(this.ffPos + 10)); }
        this.is_ff1_5up = (this.is_ff && ((this.majorVer >= 1 && this.minorVer >= 5) || (this.majorVer >= 2))); this.is_ff_closeIfrm = this.is_ff1_5up && this.majorVer < 3;
    }
    this.has_Flash = false; this.FlashVer = 0; this.detectFlash = function() {
        if (this.is_win && this.is_ie4up)
        { var dynaFrame = '<iframe id="flashDetect" src="about:blank" width="1" height="1" frameborder="0" scrolling="no" style="display:none;"></iframe>'; document.body.insertAdjacentHTML("afterBegin", dynaFrame); winObject = window["flashDetect"]; docObject = winObject.document; top.isFlashVersion = 0; top.isFlash = false; docObject.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); docObject.write('Dim hasPlayer, playerversion \n'); docObject.write('playerversion = 10 \n'); docObject.write('Do While playerversion > 0 \n'); docObject.write('On Error Resume Next \n'); docObject.write('hasPlayer = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & playerversion))) \n'); docObject.write('If hasPlayer = true Then Exit Do \n'); docObject.write('playerversion = playerversion - 1 \n'); docObject.write('Loop \n'); docObject.write('top.isFlashVersion = playerversion \n'); docObject.write('top.isFlash = hasPlayer \n'); docObject.write('</SCR' + 'IPT\>'); docObject.close(); this.has_Flash = top.isFlash; this.FlashVer = top.isFlashVersion; document.all["flashDetect"].removeNode(true); }
    }
    this.hasCookie = function(cookieName) {
        var bHasCookie = false, sCookie = document.cookie, aCookie = sCookie.split(";"); for (var i = 0; i < aCookie.length; i++) {
            while (aCookie[i].substr(0, 1) == ' ')
            { aCookie[i] = aCookie[i].substr(1); }
            if (aCookie[i].indexOf(cookieName + '=') == 0)
            { bHasCookie = true; break; }
        }
        return bHasCookie;
    }
    this.rendMode = function() {
        var m = document.compatMode; if (m) {
            if (m == "BackCompat")
            { return "Q"; }
            else if (m == "CSS1Compat")
            { return "S"; }
        }
        return "U";
    }
    this.getCurrentStyle = function(e) {
        if (window.getComputedStyle) {
            if (window.getComputedStyle(e, null))
            { return window.getComputedStyle(e, null); }
            else
            { return document.defaultView.getComputedStyle(e, null); }
        }
        else
        { return e.currentStyle; }
    }
    this.brLanguage = ""; if (this.is_ie5up)
    { this.brLanguage = navigator.browserLanguage; }
    else
    { this.brLanguage = navigator.language; }
    this.acbEvtH = false;
}
var _dapUtils = new _dapUtilClass(); var adCont = new Array(); var dapAd = new Object(); dapAd = function(qs, divid, fid, fw, fh, iA, adid, th, wc, acbO)
{ this.qs = qs; this.divid = divid; this.ifrmid = fid; this.w = fw; this.h = fh; this.isActive = iA; this.adid = adid; this.threshold = th; this.wc = wc; this.acbObj = acbO; this.documentClosed = false; this.resizeCalled = false; }
var AdControlBar = new Object(); AdControlBar = function(enabled)
{ this.enabled = enabled; this.shAcbLbl = false; this.fbFmShwn = false; this.fbSbmted = false; this.G = null; this.nS = null; this.pid = null; this.fn = null; this.mX = -1; this.xY = -1; this.noacb = false; this.lblCls = false; this.winCls = false; }
var eventType = new function()
{ this.click = 1; }; var eventPriority = new function()
{ this.special = 2; this.regular = 1; }; var dapMgr = new function() {
    this.threshold = eventType.click; this.MAX_AD_NUM = 100; this.dtRefresh = new Date().getTime(); this.REFESH_ELAPSE = 2000; this.MAX_ITR_FF = 5; this.TIME_EACH_ITR = 2000; this.renderAd = function(divid, qs, fw, fh) {
        var idx = this.getAdItemIndex(divid); if (idx > -1)
        { adCont[idx].qs = qs; adCont[idx].divid = divid; adCont[idx].w = fw; adCont[idx].h = fh; }
        else {
            if (adCont.length < this.MAX_AD_NUM) {
                var aO = new dapAd(qs, divid, 'dapIfM' + adCont.length, fw, fh, false, -1, this.threshold, 0, new AdControlBar(true)); if (_dapUtils.is_ie5)
                { adCont[adCont.length] = aO; }
                else
                { adCont.push(aO); }
            }
            else
            { return; }
            idx = adCont.length - 1;
        }
        this.displayAd(idx);
    }
    this.enableACB = function(divid, acb) {
        var idx = this.getAdItemIndex(divid); if (idx > -1)
        { adCont[idx].acb = acb; }
        else {
            if (adCont.length < this.MAX_AD_NUM) {
                var aO = new dapAd("", divid, 'dapIfM' + adCont.length, 0, 0, false, -1, this.threshold, 0, new AdControlBar(acb)); if (_dapUtils.is_ie5)
                { adCont[adCont.length] = aO; }
                else
                { adCont.push(aO); }
            }
        }
    }
    this.getAdItemIndex = function(divid) {
        var i; for (i = 0; i < adCont.length; i++) {
            if (adCont[i].divid == divid)
            { return i; }
        }
    }
    this.displayAd = function(idx) {
        var rs = _daprr[_daprs++]; if (_daprs >= _daprr.length)
        { _daprs = 0; }
        var elm = document.getElementById(adCont[idx].divid); if (!elm)
        { return; }
        if (!adCont[idx].qs || adCont[idx].qs.length == 0)
        { return; }
        if (adCont[idx].isActive)
        { return; }
        if (adCont[idx].acbObj != null && adCont[idx].acbObj.fbFmShwn)
        { return; }
        for (var i = (elm.childNodes.length - 1); i >= 0; i--) {
            var fChd = elm.childNodes[i]; if (_dapUtils.is_ff1_5up && (fChd.id == adCont[idx].ifrmid)) {
                if (fChd.contentDocument.body) {
                    while (fChd.contentDocument.body.firstChild)
                    { fChd.contentDocument.body.removeChild(fChd.contentDocument.body.firstChild); }
                }
                fChd.id = null; fChd.name = null; fChd.style.display = 'none'; fChd = null;
            }
            else {
                if (fChd.nodeName == "IFRAME" && !_dapUtils.is_ie5_5)
                { fChd.contentWindow.document.location.replace("about:blank"); }
                elm.removeChild(fChd); if (_dapUtils.is_ie5up)
                { fChd.removeNode(true); }
                else
                { fChd = null; }
            }
        }
        var elmCS = _dapUtils.getCurrentStyle(elm); if (elmCS) {
            var elmStyle = elmCS.display; if (elmStyle == "none" || elmStyle == "hidden")
            { return; }
        }
        if ((_dapUtils.is_ie5_5up || _dapUtils.is_ff1_5up) && _dapUtils.is_win) {
            var dapIfs = adCont[idx].ifrmid; var ifrm = document.createElement("IFRAME"); ifrm.id = dapIfs; ifrm.name = dapIfs; ifrm.src = "about:blank"; ifrm.width = adCont[idx].w; ifrm.height = adCont[idx].h; ifrm.scrolling = "no"; ifrm.frameBorder = "0"; ifrm.allowTransparency = true; elm.insertBefore(ifrm, elm.firstChild); if (rs.length > 0) {
                if (adCont[idx].acbObj.enabled)
                { rs += '&DPJS=' + (DPJS_ADV + DPJS_ACB); }
                else
                { rs += '&DPJS=' + DPJS_ADV; }
            }
            var str = this.getDapOutput(rs + adCont[idx].qs, dapIfs, idx); if (_dapUtils.is_ie5_5up)
            { ifrm.src = "javascript:void(document.write('" + str + "'));"; }
            else {
                ifrm.contentDocument.write(str); ifrm.contentDocument.onload = verifyDapResize(idx); if (_dapUtils.is_ff_closeIfrm)
                { window.setTimeout("checkIFrameClosed(" + idx + ",1)", this.TIME_EACH_ITR); }
                else
                { ifrm.contentDocument.close(); }
            }
            if (adCont[idx].acbObj.enabled)
            { initACB(adCont[idx].divid, idx); }
        }
        else {
            if (rs.length > 0)
            { rs += '&DPJS=' + DPJS_ADV; }
            var _dapdownlevel = true; if (parent.frames) {
                var dapIfs = adCont[idx].ifrmid; elm.innerHTML += '<iframe id="' + dapIfs + '" src="about:blank" width="' + adCont[idx].w + '" height="' + adCont[idx].h + '" frameborder="0" scrolling="no"></iframe>'; var doc; if (document.frames) {
                    if (document.frames[dapIfs])
                    { doc = document.frames[dapIfs].document; }
                }
                else {
                    if (document.getElementById(dapIfs))
                    { doc = document.getElementById(dapIfs).contentDocument; }
                }
                if (doc) {
                    _dapdownlevel = false; doc.open("text/html", "replace"); doc.write(this.getDapOutput(rs + adCont[idx].qs, dapIfs, idx)); if (_dapUtils.is_ff_closeIfrm)
                    { window.setTimeout("checkIFrameClosed(" + idx + ",1)", this.TIME_EACH_ITR); }
                    else if (!_dapUtils.is_ie)
                    { doc.close(); }
                }
            }
            if (_dapdownlevel)
            { document.write('<scr' + 'ipt src="' + rs + adCont[idx].qs + '" type="text/javascript" language="JavaScript"></scr' + 'ipt>'); adCont[idx].ifrmid = null; }
        }
    }
    this.getDapOutput = function(rs, dapIfs, idx) {
        var s = '<html><head><title>Advertisement</title></head><body id="' + dapIfs + '" leftmargin="0" topmargin="0" style="background-color:transparent"><scr' + 'ipt type="text/javascript">var inDapIF=true; var inDapMgrIf=true;'; if (document.domain && location.hostname != document.domain)
        { s += 'document.domain="' + document.domain + '";'; }
        if (_dapUtils.is_ff_closeIfrm)
        { s += 'var fnPtr=document.close;document.close=function(){parent.adCont[' + idx + '].documentClosed = true;document.close=fnPtr};'; }
        s += '</scr' + 'ipt><scr' + 'ipt type="text/javascript"  src="' + rs + '" onreadystatechange="startTimer();"></scr' + 'ipt><scr' + 'ipt type="text/javascript">function startTimer()' + '{if (event.srcElement.readyState == "complete") {parent.verifyDapResize(' + idx + ');window.setTimeout("document.close();", 2000);}}</scr' + 'ipt></body></html>'; return s;
    }
    this.trackEvent = function(evtType, evtPr) {
        var i; var isRef; if (!evtPr)
        { evtPr = eventPriority.regular; }
        for (i = 0, isRef = false; i < adCont.length; i++) {
            adCont[i].wc += (evtType * evtPr); var tElp = (new Date()).getTime() - this.dtRefresh; if ((adCont[i].wc >= adCont[i].threshold) && (tElp > this.REFESH_ELAPSE)) {
                adCont[i].wc = 0; if (adCont[i].threshold > -1 && adCont[i].ifrmid != null) {
                    this.displayAd(i); isRef = true; if (adCont[i].acbObj.enabled && adCont[i].acbObj.fbSbmted)
                    { adCont[i].acbObj.fbSbmted = false; }
                }
            }
        }
        if (isRef)
        { this.dtRefresh = (new Date()).getTime(); }
    }
}; function checkIFrameClosed(idx, iterations) {
    var ifrm = document.getElementById(adCont[idx].ifrmid); if (ifrm) {
        if (iterations >= dapMgr.MAX_ITR_FF && !adCont[idx].documentClosed)
        { ifrm.contentDocument.close(); }
        if (adCont[idx].documentClosed) {
            try
{ ifrm.contentDocument.close(); }
            catch (e) { }
        }
        else
        { window.setTimeout("checkIFrameClosed(" + idx + "," + (iterations + 1) + ")", dapMgr.TIME_EACH_ITR); }
    }
}
function acbAdResize(df, w, h) {
    for (var i = 0; i < adCont.length; i++) {
        if (adCont[i].ifrmid == df) {
            if (w < acbMinWdth) {
                adCont[i].acbObj.noacb = true; if (_dapUtils.acbEvtH)
                { _acb.removeACBLabel(i); }
            }
            else {
                if (_dapUtils.acbEvtH)
                { _acb.showACBLabel(i); }
            }
            adCont[i].w = w; adCont[i].h = h; var o = document.getElementById(adCont[i].divid); if (o) {
                o.style.width = w + "px"; if (_dapUtils.is_ff1_5up && _dapUtils.rendMode() == "S" && h > 1) {
                    var dh = h; if (!adCont[i].acbObj.noacb && adCont[i].acbObj.enabled)
                    { dh += acbAdBarH; }
                    o.style.height = dh + "px";
                }
            }
            var ol = document.getElementById("acbLblfrm" + i); if (ol)
            { ol.style.width = w + "px"; }
            adCont[i].resizeCalled = true; return;
        }
    }
}
function initACB(divid, Id) {
    if (!_dapUtils.acbEvtH) {
        if (!acbDwnLdSt)
        { acbDwnLdSt = true; var d = document.createElement("SCRIPT"); d.type = "text/javascript"; d.language = "javascript"; d.src = _daplp + "/ACB/acb.js"; document.body.insertBefore(d, document.body.firstChild); }
    }
    else
    { _acb.initACBLabel(Id); }
}
function ShowAcb(idStr, adId, W, H, G, nS, pid, fn) {
    var Id = acbGetIdFrmIdStr(idStr); if (Id > -1) {
        adCont[Id].adid = adId; adCont[Id].w = W; var acbO = adCont[Id].acbObj; acbO.shAcbLbl = true; acbO.fn = fn; acbO.G = G; acbO.nS = nS; acbO.pid = pid; if (_dapUtils.acbEvtH)
        { _acb.showACBLink(Id); }
        return;
    }
}
function acbGetIdFrmIdStr(s) {
    var id = s.substring(6, s.length); if (id >= 0)
    { return id; }
    else
    { return -1; }
}


///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////core.js//////////////////////////////////////////////////
Function.prototype.addMethod = function(a, b) { if (!this.prototype[a]) this.prototype[a] = b; return this };
Function.addMethod("as", function(e, f) {
  var b = e ? e.split(".") : []; if (b.length > 0)
  { var a = window; for (var d = 0; d < b.length - 1; ++d) { var c = b[d]; if (c) { if (!a[c]) a[c] = {}; a = a[c] } } a[b.last()] = f ? new this : this } return this
});
Function.addMethod("ns", function(a) { this.as(a, 1) }); String.addMethod("trim", function() { return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1") }); String.addMethod("collapse", function() { return this.replace(/\s+/g, " ").trim() }); String.addMethod("wrap", function(a) { var b, c = { "(": ")", "{": "}", "[": "]", "<": ">", "\u00c2\u00ab": "\u00c2\u00bb", "\u00e2\u20ac\u00b9": "\u00e2\u20ac\u00ba", "\u00e2\u20ac\u0153": "\u00e2\u20ac\u009d", "\u00e2\u20ac\u02dc": "\u00e2\u20ac\u2122" }; if (c[a]) b = c[a]; else { var d = /^<(\w+)(\s+\w+\s*=\s*"[^"]*")*\s*>$/.exec(a); if (d) b = "</" + d[1] + ">" } return a + this + (b ? b : a) }); String.addMethod("format", function() { var b = this; for (var a = 0; a < arguments.length; ++a) b = b.replace(new RegExp("\\{" + a + "\\}", "g"), arguments[a]); return b }); String.addMethod("encodeHtml", function() { var a = this.replace(/\>/g, "&gt;").replace(/\</g, "&lt;").replace(/\&/g, "&amp;").replace(/\'/g, "&#039;").replace(/\"/g, "&quot;"); return a }); String.addMethod("decodeHtml", function() { var a = this.replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&amp;/g, "&").replace(/&#039;/g, "'").replace(/&quot;/g, '"'); return a }); String.addMethod("encodeURIComponent", function() { return typeof encodeURIComponent != "undefined" ? encodeURIComponent(this) : escape(this) }); String.addMethod("decodeURIComponent", function() { return typeof decodeURIComponent != "undefined" ? decodeURIComponent(this) : unescape(this) }); Array.addMethod("last", function() { return this.length > 0 ? this[this.length - 1] : void 0 }); Array.addMethod("remove", function(b) { for (var a = this.length - 1; a >= 0; --a) if (this[a] === b) this.splice(a, 1); return this }); Array.addMethod("contains", function(b) { for (var a = 0; a < this.length; ++a) if (this[a] === b) return 1; return 0 }); Array.addMethod("push", function(a) { this[this.length] = a; return this.length }); Array.addMethod("shift", function() { return this.splice(0, 1)[0] }); Array.addMethod("splice", function(c, d) { var b, e = arguments.length - 2; if (c > this.length) c = this.length; if (c + d > this.length) d = this.length - c; var f = []; for (var a = 0; a < d; ++a) f.push(this[c + a]); if (e > d) { b = e - d; for (a = this.length + b - 1; a >= c + b; --a) this[a] = this[a - b] } else if (e < d) { b = d - e; for (a = c + e; a < this.length - b; ++a) this[a] = this[a + b]; for (; a < this.length - 1; ++a) delete this[a]; this.length -= b } for (a = 0; a < e; ++a) this[c + a] = arguments[2 + a]; return f }); (function() { var a = this; Function.addMethod("hook", function(d, e) { if (d) { var f = b(); if (!f && d.addEventListener) d.addEventListener(e, this, false); else if (!f && d.attachEvent) d.attachEvent("on" + e, this); else { var c = d["x" + e]; if (c && c.constructor == Array) if (c.contains(this)) c = null; else c.push(this); else c = d["x" + e] = [this]; if (c) { d["on" + e] = function(d) { var f = true; d = a.Event(d); for (var b = 0; b < c.length; ++b) { var e = c[b](d); if (typeof e != "undefined" && !e) f = false } return f }; d = null } } } return this }); Function.addMethod("unhook", function(a, c) { if (a) { var e = b(); if (!e && a.removeEventListener) a.removeEventListener(c, this, false); else if (!e && a.detachEvent) a.detachEvent("on" + c, this); else { var d = a["x" + c]; if (d && d.constructor == Array) d.remove(this); else a["on" + c] = null } } return this }); a.CancelEvent = function(b) { b = a.Event(b); if (b) { b.cancelBubble = true; if (b.stopPropagation) b.stopPropagation(); b.returnValue = false; if (b.preventDefault) b.preventDefault() } return false }; a.Event = function(a) { return a ? a : window.event }; a.Target = function(c) { c = a.Event(c); var b = c.target ? c.target : c.srcElement; if (b && b.nodeType != 1) b = a.ParentElem(b); return b }; a.InnerText = function(e) { var c = ""; for (var d = 0; d < e.childNodes.length; d++) { var b = e.childNodes[d]; if (b.nodeType == 1) c += a.InnerText(b); else if (b.nodeType == 3) c += b.data } return c }; a.NextElem = function(c, b) { var a = c.nextSibling; while (a && (a.nodeType != 1 || b && a.nodeName != b)) a = a.nextSibling; return a }; a.PrevElem = function(c, b) { var a = c.previousSibling; while (a && (a.nodeType != 1 || b && a.nodeName != b)) a = a.previousSibling; return a }; a.ParentElem = function(c, b) { var a = c.parentNode; while (a && (a.nodeType != 1 || b && a.nodeName != b)) a = a.parentNode; return a }; a.ChildElem = function(e, f, g) { var d = null, b; for (var c = 0; !d && c < e.childNodes.length; ++c) { b = e.childNodes[c]; if (b.nodeType == 1) if (!f || b.nodeName == f) d = b } if (!g) for (c = 0; !d && c < e.childNodes.length; ++c) { b = e.childNodes[c]; if (b.nodeType == 1) d = a.ChildElem(b, f) } return d }; a.ForEach = function(e, d, c) { for (var b = 0; b < d.childNodes.length; ++b) { var a = d.childNodes[b]; if (a.nodeType == 1 && (!c || a.nodeName == c)) if (e(a)) break } }; a.ChildCount = function(d, c) { var e = 0, a, b; for (a = 0; a < d.childNodes.length; ++a) { b = d.childNodes[a]; e += b.nodeType == 1 && (!c || b.nodeName == c) ? 1 : 0 } return e }; a.AddClass = function(a, e) { var c = a.className; if (c) { var g = c.collapse().split(" "), d = e.collapse().split(" "); for (var b = 0; b < d.length; ++b) { var f = d[b]; if (!g.contains(f)) a.className += " " + f } } else a.className = e; return a.className }; a.DelClass = function(b, g) { var a = b.className; if (a) { var f = a.collapse().split(" "), d = g.collapse().split(" "); for (var c = 0; c < d.length; ++c) f.remove(d[c]); var e = f.join(" "); if (e != a) b.className = e } return b.className }; a.HasClass = function(b, a) { return b.className.collapse().split(" ").contains(a) }; a.Updated = function() { if (a.Access && typeof a.Access.Updated == "function") a.Access.Updated() }; function b() { return navigator.userAgent.indexOf("Safari") >= 0 } }).ns("Msn.DOM"); (function() { var a = this, c = []; Function.addMethod("bind", function(b, h) { var d; switch (typeof b) { case "object": d = b.nodeType == 1 || b.nodeType == 9 ? [b] : b.length ? b : null; break; case "string": d = a.Select(b) } if (d) for (var g = 0; g < d.length; ++g) { var e = d[g], f = new this(e, h); if (e.bindings) e.bindings.push(f); else e.bindings = [f]; c.push(f) } return this }); a.Unbind = function(d, f) { var b; if (d.bindings && d.bindings.length) { for (b = 0; b < d.bindings.length; ++b) { var e = d.bindings[b]; if (e && typeof e.dispose == "function") e.dispose(); c.remove(e) } d.bindings = null } if (f) for (b = 0; b < d.childNodes.length; ++b) { var g = d.childNodes[b]; if (g.nodeType == 1) a.Unbind(g, f) } }; a.Select = function(c) { function i() { var d = null; if (c) if (c.charAt(a) == "*") d = "*"; else while (a < c.length) { var b = c.charAt(a); if ("a" <= b && b <= "z" || "A" <= b && b <= "Z" || "0" <= b && b <= "9" || b == "-") { d = d ? d + b : b; ++a } else break } return d } function j() { while (a < c.length && c.charAt(a) == " ") ++a } function m() { var b = null; j(); switch (c.charAt(a)) { case "+": case ">": b = c.charAt(a); ++a; j() } return b } function h() { ++a; return i() } function g() { var b = null, d = i(); if (d !== null) b = new e(d); while (c && a < c.length) { var f = c.charAt(a); if (f == "#") { if (!b) b = new e; b.setID(h()) } else if (f == ".") { if (!b) b = new e; b.addClass(h()) } else break } return b } function n() { var d = [], b = g(); if (b) { d.push(b); while (a < c.length) { var e = m(); b = g(); if (b) { if (e) b.setComb(e); d.push(b) } else break } } return d } function e(a) { var g = this, e = "", f = null, d = null; g.setID = function(a) { e = a }; g.setComb = function(a) { f = a }; g.addClass = function(a) { if (d) d.push(a); else d = [a] }; g.getNodes = function(i) { var d, g, j, k = []; if (e) { switch (f) { case ">": for (d = 0; d < i.childNodes.length; ++d) if (i.childNodes[d].nodeType == 1 && i.childNodes[d].id == e) { g = i.childNodes[d]; break } break; case "+": j = b(i); if (j && j.id == e) g = j; break; default: g = i.getElementById(e) } if (g && (!a || a == "*" || a.toLowerCase() == g.nodeName.toLowerCase()) && c(g)) k.push(g) } else if (a && a != "*") switch (f) { case ">": for (d = 0; d < i.childNodes.length; ++d) { g = i.childNodes[d]; if (g.nodeType == 1 && g.nodeName.toLowerCase() == a && c(g)) k.push(g) } break; case "+": j = b(i); if (j && j.nodeName.toLowerCase() == a && c(j)) k.push(j); break; default: var l = i.getElementsByTagName(a); for (d = 0; d < l.length; ++d) if (c(l[d])) k.push(l[d]) } else switch (f) { case ">": for (d = 0; d < i.childNodes.length; ++d) { g = i.childNodes[d]; if (g.nodeType == 1 && c(g)) k.push(g) } break; case "+": j = b(i); if (j && c(j)) k.push(j); break; default: h(i, k) } return k }; function h(d, e) { for (var b = 0; b < d.childNodes.length; ++b) { var a = d.childNodes[b]; if (a.nodeType == 1) { if (c(a)) e.push(a); h(a, e) } } } function c(f) { var a = 1; if (d) { var c = f.className; if (c) { var e = c.collapse().split(" "); for (var b = 0; b < d.length; ++b) if (!e.contains(d[b])) { a = 0; break } } else a = 0 } return a } } function l(c, d) { var a = []; for (var b = 0; b < c.length; ++b) a = a.concat(d.getNodes(c[b])); return a } var a = 0, k = n(), d = [document]; for (var f = 0; f < k.length && d.length > 0; ++f) d = l(d, k[f]); return d }; function b(b) { var a = b.nextSibling; while (a && a.nodeType != 1) a = a.nextSibling; return a } (function() { a.Unbind(document, 1); c = [] }).hook(window, "unload") }).ns("Msn.Bind"); (function(j, e) { if (!e) e = {}; var g = Msn.DOM, d = document, k = window, c = d.getElementById("more"); c.style.display = "none"; var f = d.getElementById("xnav"), b = d.createElement("li"), a = d.createElement("a"); a.href = "#"; a.className = "expand"; a.innerHTML = h(e.more, "more"); b.appendChild(a); f.appendChild(b); i.hook(a, "click"); function i(f) { var d = c.style.display, e; if (d == "block") { d = "none"; e = "expand"; b.className = "" } else { d = "block"; e = "collapse"; b.className = "last" } c.style.display = d; a.className = e; f = g.Event(f); return g.CancelEvent(f) } this.dispose = function() { j = null; c = null; f = null; b = null; a = null }; function h(a, b) { return typeof a != "undefined" ? a : b } }).as("Msn.Header"); (function(p, b) { if (!b) b = {}; var d = Msn.DOM, e = document, q = window, k = c(b.searchParam, ""), g = c(b.searchParams, ""), h = c(b.searchSite, ""), m = c(b.searchUrl, ""), n = c(b.searchWeb, ""); if (h !== "") { var j = e.getElementById("sitesearch"), a = e.createElement("input"); a.className = "button"; a.id = "site"; a.name = "site"; a.type = "submit"; a.value = h; j.appendChild(a); var l = e.getElementById("web"); l.value = n; f.hook(a, "click"); var i = e.getElementById("q"); o.hook(i, "keypress") } function o(a) { if (a.keyCode == 13) { f(null); a = d.Event(a); return d.CancelEvent(a) } } function f(a) { if (a !== null) if (d.Target(a).id != "site") return; var c = encodeURIComponent(e.getElementById("q").value), b = m + "?" + k + "=" + c; if (g) b = b + "&" + g.replace(/&amp;/g, "&"); window.top.location.href = b; a = d.Event(a); return d.CancelEvent(a) } this.dispose = function() { p = null }; function c(a, b) { return typeof a != "undefined" ? a : b } }).as("Msn.SiteSearch")


﻿function ajaxObject(url, callbackFunction) 
{
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) 
  { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.setRequestHeader("Content-Length", passData.length);
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}
