﻿var NumberOfTopFavorites = 3;
var InitialNumberOfProperties = 20;
var NumberOfPropertiesInStep = 20;
var InfoTimerInterval = 12 * 1000;
var ProgressTimerInterval = 25 * 1000;
var MaxPropertiesToDisplay = 300;
var EmptyImageUrl = 'http://davidgriffin.com/listingimages/PropImage.gif';

var aryAdsRandom = new Array();
var aryAdsHeader = new Array();
var objCurAdsHeader = null;
var lastAdsCounter = 1;
var aryAdsAll = new Array();
var curAdsRandomIndex = 0;

var aryShortList = new Array();
var aryProperties = new Array();
var objPropertyLastDeleted = null;
var objShortlistLastDeleted = null;
var aryLoadedRows = new Array();
var aryNumberOfPropertiesPerRow = new Array();
var totalItems = 0;
var timerInfo = null;
var timerLoader = null;
var timerProgress = null;
var timerAds = null;

var isMapCompatible = false;

var iconGriffin;
var iconMLS;

var hashPrevValues = new Object();

var hashMaps = new Hashtable();
var pageMode = 'Grid';
var largeMap = null;

var hashActiveSddl = new Hashtable();

Array.prototype.clear = function() {
    this.length = 0;
}

Array.prototype.has = function(v,i) {
    for (var j = 0; j < this.length; j++) {
        if (this[j] == v) return (!i ? true : j);
    }
    return false;
}

Array.prototype.indexOf = function(v) {
    for (var j = 0; j < this.length; j++) {
        if (this[j] == v) return j;
    }
    return -1;
}

Array.prototype.removeAt = function(iIndex) {
    var vItem = this[iIndex];
    if (vItem) {
        this.splice(iIndex, 1);
    }
    return vItem;
};

function PropertyObj(listingId, address, price, priceSearch, imageLg, listingInfo, zip, isGriffin, coord1, coord2, hasShortlist) {
    // Properties
    this.ListingId = listingId;
    this.Address = address;
    this.Price = price.toString().replace('<BR>', ', ').replace('<br>', ', ');
    this.PriceSearch = priceSearch;
    this.ImageLg = imageLg;
    this.ListingInfo = listingInfo.toString().replace(' <BR>', ', ');
    this.ZipCode = zip;
    this.IsGriffin = (isGriffin == 1 ? true : false);
    this.Coord1 = coord1;
    this.Coord2 = coord2;
    this.IsInShortlist = (hasShortlist == 0 ? false : true);
    this.RenderedRow = -1;

    this.IsImagesLoaded = false;
    this.IsInfoLoaded = false;

    this.HasWrongInitialImage = false;

    this.Images = new Array();

    this.LongDescription = "";
    this.BathroomsNo = "";
    this.BedroomsNo = "";
    this.GaragesNo = "";
    this.Sqft = "";
    this.SqftSource = "";

    this.IsInfoDisplayed = false;
    this.IsMapDisplayed = false;
    this.IsLargeMapDisplayed = false;

    this.Overlay = null;

    // Methods
    this.addImage = PropertyObj_AddImage;
    this.addImagesAsStr = PropertyObj_AddImagesAsStr;
    this.setDetailInfo = PropertyObj_SetDetailInfo;
    this.hasImages = PropertyObj_HasImages;
    this.hasMapCoords = PropertyObj_HasMapCoords;
    this.setOverlay = PropertyObj_SetOverlay;
    this.removeImageByUrl = PropertyObj_RemoveImageByUrl;
}

function PropertyObj_RemoveImageByUrl(img) {
    for (var i = 0; i < this.Images.length; i++) {
        if (this.Images[i] == img) {
            this.Images.splice(i, 1);
            return;
        }
    }
}

function PropertyObj_AddImage(img) {
    if (img == EmptyImageUrl || img == '') return;
    if (this.Images.has(img)) return;

    this.Images.push(img);
}

function PropertyObj_AddImagesAsStr(images) {
    var ary = images.split(',');
    for (var i = 0; i < ary.length; i++) {
        if (ary[i] == '' || ary[i] == EmptyImageUrl) continue;
        if (this.Images.has(ary[i])) continue;

        this.Images.push(ary[i]);
    }
}

function PropertyObj_HasImages() {
    return this.Images.length == 0 ? false : true;
}

function PropertyObj_HasMapCoords() {
    if (!isMapCompatible) return false;
    return this.Coord1 == 0 && this.Coord2 == 0 ? false : true;
}

function PropertyObj_SetOverlay(newOverlay) {
    this.Overlay = newOverlay;
}

function PropertyObj_SetDetailInfo(obj) {
    this.LongDescription = obj.desc_long;
    this.BathroomsNo = obj.bathrooms_no;
    this.BedroomsNo = obj.bedrooms_no;
    this.GaragesNo = obj.garage_no;
    this.Sqft = obj.sqft;
    this.SqftSource = obj.sqft_source;

    if (trim(this.Sqft + " " + this.SqftSource) == "0") {
        this.Sqft = "";
        this.SqftSource = "";
    }
}

function ID(id) { return document.getElementById(id); }

function SetProgress(text, bUseTimer) {
    if (bUseTimer == undefined) bUseTimer = false;

    if (timerProgress) clearTimeout(timerProgress);

    if (ID('absdiv')) {
        ID('absdiv').innerHTML = text;

        if (bUseTimer) timerProgress = setTimeout('OnProgressTimerTick()', ProgressTimerInterval);
    }
}

function ClearProgress() {
    SetProgress('');
}

function OnProgressTimerTick() {
    clearTimeout(timerProgress);

    if (ID('absdiv')) {
        ID('absdiv').innerHTML = '';
    }
}

function SetBottomInfo(text) {
    if (ID('bottomdiv')) {
        ID('bottomdiv').innerHTML = text;
        if (timerInfo) clearTimeout(timerInfo);
        timerInfo = setTimeout('OnInfoTimerTick()', InfoTimerInterval);
    }
}

function OnInfoTimerTick() {
    clearTimeout(timerInfo);

    if (ID('bottomdiv')) {
        ID('bottomdiv').innerHTML = '';
    }
}

function GetPropertyValue(name) {
    var form = window.document.forms[0];
    var hiddenFields = form.getElementsByTagName('input');

    for (var i = 0; i < hiddenFields.length; i++) {
        if (hiddenFields[i].type == 'hidden') {
            if (hiddenFields[i].name.indexOf(name) >= 0)
                return hiddenFields[i].value;
        }
    }

    return '';
}

function SetPropertyValue(name, val) {
    var form = window.document.forms[0];
    var hiddenFields = form.getElementsByTagName('input');

    for (var i = 0; i < hiddenFields.length; i++) {
        if (hiddenFields[i].type == 'hidden') {
            if (hiddenFields[i].name.indexOf(name) >= 0)
                hiddenFields[i].value = val;
        }
    }
}

function GetUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function GetVItem(bFull) {
    if (bFull == undefined) bFull = false;

    var hash = GetUrlVars();
    var item = "";

    try {
        item = hash["v"];
    }
    catch(e) {
    }

    if (bFull) return item;

    if (item.indexOf("#") >= 0) {
        var ret = item.substr(item.indexOf("#") + 1);
        if (ret.substr(0, 1) == 'i')
            ret = ret.substr(1);

        if (isDecimal(ret)) return ret;
    }

    return '';
}

function GetVItem2() {
    var hash = GetUrlVars();
    var item = "";

    try {
        item = hash["v"];
    }
    catch (e) {
    }

    if (item.indexOf("#") >= 0) return item.substring(0, item.indexOf("#"));

    return item;
}

function SetTopInfoLabel() {
    var typeId = parseInt(GetPropertyValue('TypeId'));

    var lbl = "";
    var pageTitle = "Buy a House, Condo or Townhouse  in Dallas, Texas - David Griffin & Co Realtors";
    var pageDescr = "Buy or Lease a new house, condo or townhouse with Dallas, Texas based David Griffin and Co Realtors.  Choose from Downtown, Turtle Creek, Highland Park, Lakewood or other Dallas neighborhoods.";
    if (typeId == 0) {
        lbl = "FEATURED PROPERTIES";
        if (GetVItem() != "") {
            pageTitle = "Featured Condo, House & Townhouse property listings in Dallas, Texas - David Griffin & Co Realtors";
            pageDescr = "Browse the featured property listings in a variety of Dallas Neighborhoods such as Downtown, Turtle Creek, Highland Park, and many others. View condos, houses and townhomes ready to lease or buy from David Griffin and Co Realtors.";
        }
    }
    if (typeId == 1) {
        lbl = "DG&Co. OPEN HOUSES";
        pageTitle = "Condos, Houses & Townhouse Open House in Dallas, Texas - David Griffin & Co Realtors";
        pageDescr = "Find David Griffin and Co Realtors’ upcoming open houses in Downtown, Oak Cliff, Highland Park and other Dallas Neighborhoods. View townhouses, condos and houses available for sale or lease.";
    }
    if (typeId == 2) {
        lbl = "NEW LISTINGS";
        pageTitle = "New Condo, House and Townhouse property listings in Dallas, Texas - David Griffin & Co Realtors";
        pageDescr = "Find out about new condo, house and townhouse property listings available in the Dallas Texas area. David Griffin and Co Realtors brings the best from Downtown, Oak Lawn, Highland Park and other Dallas neighborhoods.";
    }
    if (typeId == 3) {
        lbl = "FILTERED LIST";
        pageTitle = "Filtered Condo, House & Townhouse property listings - David Griffin & Co Realtors";
    }
    if (typeId == 4) {
        lbl = "FAVORITES LIST";
        pageTitle = "Favorite Condo, House & Townhouse property listings - David Griffin & Co Realtors";
    }
    if (typeId == 5) {
        lbl = "FILTERED LIST";
        pageTitle = "Filtered Condo, House & Townhouse property listings - David Griffin & Co Realtors";
    }
    if (typeId == 6) {
        lbl = "DG&Co LISTINGS";
        pageTitle = "Condo, House & Townhouse property listings for sale or lease in Dallas, Texas - David Griffin & Co Realtors";
        pageDescr = "View listings in Downtown, Turtle Creek, Highland Park, Oak Lawn and other Dallas Neighborhoods. From condos and townhouses to lots and houses, see what David Griffin and Co Realtors has available.";
    }
    if (typeId == 7) {
        lbl = "MODERN LISTINGS";
        pageTitle = "Modern Living Condo and House Property Listings in Dallas, Texas - David Griffin & Co Realtors";
        pageDescr = "View the most unique Modern living condos and houses in Dallas, Texas. David Griffin and Co Realtors specializes in bringing you the best in Modern Living in the hippest Dallas neighborhoods.";
    }

    $("#lblInfo1").html(lbl);
    document.title = pageTitle;

    window.location = window.location.href.replace('?v=' + GetVItem(true), '?v=' + GetVItem2() + '#i' + typeId);
    $("meta[name=description]").attr("content", pageDescr);
}

function HighlightLeftBtn() {
    var typeId = parseInt(GetPropertyValue('TypeId'));

    var btn = '';
    if (typeId == 0) btn = "FeaturedPropertiesClientId";
    if (typeId == 1) btn = "OpenHousesClientId";
    if (typeId == 2) btn = "NewListingsClientId";
    if (typeId == 6) btn = "DGListingsClientId";
    if (typeId == 7) btn = "ModernHousesClientId";

    if (btn != '') ResetLeftButtonsStyle(btn);
}

function PageInit(bSecondCall) {
    if (bSecondCall == undefined) bSecondCall = true;

    hashPrevValues['PageMode'] = pageMode;
    hashPrevValues['STypes'] = GetControlValue(ID(GetPropertyValue('STypesClientId')));

    if (GetPropertyValue('Page') == "Default") {
        $("#divLargeMapContainer").hide();
        $("#" + GetPropertyValue('LoadNextClientId')).hide();
        SetTopInfoLabel();
        HighlightLeftBtn();

        InitGMaps();
    }
    else if (GetPropertyValue('Page') == "Print") {
        InitGMaps();
    }

    if (!bSecondCall && (GetPropertyValue('NewType') == 'Detail Search' || GetPropertyValue('NewPageMode') == "Search")) {
        OnClickDetailedSearch();
    }
    else if (GetPropertyValue('Page') == 'Default' || GetPropertyValue('Page') == 'Print')
        InitialLoadProperties();
}

function OnPageInit() {
    RestorePrevState();

    InitIcons();
    if(GetPropertyValue('Page') != 'Print')
        LoadShortlist();

    PageInit(false);
}

function SetMapSwitchImages() {
    if (!GetPropertyValue('ListResultsClientId')) return;

    var imgList = ID(GetPropertyValue('ListResultsClientId'));
    if (!imgList) return;

    var imgMap = ID(GetPropertyValue('MapResultsClientId'));
    if (!imgMap) return;

    var curPageMode = GetCurrentPageMode();
    if (curPageMode == 'Grid') {
        imgList.src = 'images/06-list-results-on.png';
        imgMap.src = 'images/06-map-results.png';
    }
    else {
        imgList.src = 'images/06-list-results.png';
        imgMap.src = 'images/06-map-results-on.png';
    }
}

function RestorePrevState() {
    if (GetPropertyValue('NewPageMode') != '') pageMode = GetPropertyValue('NewPageMode');
    SetMapSwitchImages();

    var newType = GetPropertyValue('NewType');
    if (newType == '') return;

    if (GetPropertyValue('Page') != 'Print') {
        SetPropertyValue('Filter', '');
        SetPropertyValue('MLSNumbers', '');
    }

    if (newType == 'Featured Properties') SetPropertyValue('TypeId', 0);
    if (newType == 'DG&Co Listings') SetPropertyValue('TypeId', 6);
    if (newType == 'Modern Houses') SetPropertyValue('TypeId', 7);
    if (newType == 'Open Houses') SetPropertyValue('TypeId', 1);
    if (newType == 'New Listings') SetPropertyValue('TypeId', 2);
    if (newType == 'Quick Search') {
        SetPropertyValue('TypeId', 3);
        if(GetPropertyValue('Page') != 'Print') SetPropertyValue('Filter', GetFilterExpression(true));
    }
    if (newType == 'Favorites') SetPropertyValue('TypeId', 4);
    if (newType == 'Detail Search' && GetPropertyValue('Page') == 'Default') {
        SetPropertyValue('TypeId', 5);
        if (GetPropertyValue('Page') != 'Print') {
            SetPropertyValue('Filter', GetFilterExpression(false));
            SetPropertyValue('MLSNumbers', GetMLSNumbers());
        }
    }
}

function InitialLoadProperties() {
    if (GetMaxIndex() == 0) SetPropertyValue('NumberOfProperties', InitialNumberOfProperties);

    aryProperties.clear();
    aryLoadedRows.clear();
    aryNumberOfPropertiesPerRow.clear();
    hashMaps.clear();
    if (largeMap) largeMap.clearOverlays();
    totalItems = 0;

    $("#divcontainer").hide();
    $("#divLargeMapContainer").hide();

    LoadAds();
    //LoadListings();
}

function LoadAds() {
    if (GetPropertyValue('Page') == 'Default' || GetPropertyValue('Page') == 'Print') {
        SetProgress('Loading...');

        if (timerAds) clearTimeout(timerAds);

        aryAdsHeader.clear();
        aryAdsRandom.clear();
        aryAdsAll.clear();
        curAdsRandomIndex = 0;
        lastAdsCounter = 1;
        objCurAdsHeader = null;

        DG2WebService.AdsGetList(AdsGetList_Callback);
    }
}

function AdsGetList_Callback(result) {
    for (var i = 0; i < result.length; i++) {
        var obj = result[i];
        if (obj.Type_Int == 1) aryAdsHeader.push(obj);
        if (obj.Type_Int == 2) aryAdsRandom.push(obj);
    }

    if (result.length > 0)
        timerAds = setInterval('timerAds_Tick()', 1 * 1000);

    LoadListings();
}

function timerAds_Tick() {
    for (var i = 0; i < aryAdsAll.length; i++)
        if (aryAdsAll[i].AutoScroll && aryAdsAll[i].Images.length > 1) {
            if (aryAdsAll[i].LastSwitchTime >= aryAdsAll[i].SwitchTime) {
                OnClickChangeAdsImage(aryAdsAll[i].CounterId, 1, true, false);
                aryAdsAll[i].LastSwitchTime = 0;
            }
            else
                aryAdsAll[i].LastSwitchTime++;
        }
}

function LoadListings() {
    if (GetPropertyValue('Page') == 'Default' || GetPropertyValue('Page') == 'Print') {
        totalItems = 0;
        SetProgress('Loading listings...');
        DG2WebService.ListingSimpleGetList(GetPropertyValue('TypeId'), GetPropertyValue('Filter'), GetPropertyValue('SessionId'), GetPropertyValue('MLSNumbers'), OnLoadListings);

        // Event to detect scrolling.
        if (GetPropertyValue('Page') == 'Default')
            StartPolling();
    }
}

function OnLoadListings(result) {
    aryProperties.clear();
    hashMaps.clear();

    for (var i = 0; i < result.length; i++) {
        aryProperties.push(new PropertyObj(result[i].listing_id, result[i].address, result[i].price, result[i].price_search, result[i].image_lg, result[i].listing_info, result[i].zip, result[i].is_Griffin, result[i].coord1, result[i].coord2, result[i].has_shortlist));
    }

    SetBottomInfo('' + aryProperties.length + (aryProperties.length >= MaxPropertiesToDisplay ? '+' : '') + ' properties found');
    ClearProgress();
    $("#divLoading").hide();
    if (pageMode != 'Search') {
        $("#divInfoPanel").show();

        if (pageMode != 'LargeMap')
            $("#divcontainer").show();
        else
            $("#divLargeMapContainer").show();
    }

    SetLoadNextControls();

    GenerateHeaderAds();
    CreateListingObjHtmlElements();
    MapProperties();
    LoadPropertyDetails();
}

function GetRandomNumber(start, end) {
    if (start == end) return start;

    return Math.floor((end - start) * Math.random()) + start;
}

function GetLastAdsId() {
    var retId = lastAdsCounter;
    lastAdsCounter++;

    return retId;
}

function HasAdsInAll(adsCounterId) {
    for (var i = 0; i < aryAdsAll.length; i++)
        if (aryAdsAll[i].CounterId == adsCounterId)
            return true;

    return false;
}

function GenerateHeaderAds() {
    if (aryAdsHeader.length == 0) return;

    var container = $("#divcontainer");
    if (!container) return;

    var adsIndex = GetRandomNumber(0, aryAdsHeader.length);
    if (adsIndex >= aryAdsHeader.length) adsIndex = 0;
    var objAds = aryAdsHeader[adsIndex];
    objAds.CounterId = GetLastAdsId();

    $("<div />")
        .attr("id", "divAds" + objAds.CounterId)
        .addClass("l-container")
        .appendTo(container);

    var c = $("#divAds" + objAds.CounterId);

    $("<div />")
        .addClass("l-ads-h2x1")
        .appendTo(c)
        .append('<div id="divAds_Rel' + objAds.CounterId + '" class="relpos"></div>')
        .append('<img id="imgAds' + objAds.CounterId + '" src="' + objAds.Images[0] + '" title="' + objAds.Title + '" class="l-img-ads-h2x1 hand" onload="OnAdsImageLoad(' + objAds.CounterId + ');" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', 1, true);" />')
        .append('<div id="pnlI_Ads' + objAds.CounterId + '" class="l-det-ads-h2x1" style="display: none;">' + objAds.Descr + '</div>')
//        .append('<div id="divAdsbL' + objAds.CounterId + '" class="l-info-ads-h2x1 fLeft"></div>')
//        .append('<div id="divAdsbR' + objAds.CounterId + '" class="l-nav-ads-h2x1 fLeft"></div>')
        .append('<div class="clear"></div>');

//    c = $("#divAdsbL" + objAds.CounterId);

//    // Title.
//    $("<div />")
//        .addClass("l-address")
//        .html(objAds.Title)
//        .appendTo(c);

//    // Short description.
//    $("<div />")
//        .addClass("l-price")
//        .html(objAds.ShortDescr)
//        .appendTo(c);

//    c = $("#divAdsbR" + objAds.CounterId);

//    $("<div />")
//        .attr("id", "divAdsbR_1_" + objAds.CounterId)
//        .addClass("tcenter mt9")
//        .appendTo(c);

//    $("<div />")
//        .attr("id", "divAdsbR_2_" + objAds.CounterId)
//        .addClass("tcenter mt9")
//        .appendTo(c);

//    // Navigation.
//    $("#divAdsbR_1_" + objAds.CounterId)
//        .append('<img src="images/06-left.png" title="Previous Image" style="cursor: pointer;' + (objAds.Images.length == 1 && objAds.Descr == '' ? 'display:none;' : '') + '" onmouseover="this.src=\'images/06-left-h.png\'" onmouseout="this.src=\'images/06-left.png\'" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', -1);" />')
//        .append('<img src="images/06-right.png" title="Next Image" style="cursor: pointer;' + (objAds.Images.length == 1 && objAds.Descr == '' ? 'display:none;' : '') + '" onmouseover="this.src=\'images/06-right-h.png\'" onmouseout="this.src=\'images/06-right.png\'" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', 1);" />');

    $("<div />")
        .attr("id", "pnlF_Ads" + objAds.CounterId)
        .attr("align", "center")
        .attr("valign", "middle")
        .addClass("l-img-ads-h2x1 fadediv-ads-h2x1")
        .append('<img src="images/ajax-loader.gif" title="Image Loader" class="fadediv-ads-h2x1" onclick="OnAdsImageLoaderClick(' + objAds.CounterId + ');" />')
        .appendTo($("#divAds_Rel" + objAds.CounterId));

    objCurAdsHeader = objAds;

    if (!HasAdsInAll(objAds.CounterId))
        aryAdsAll.push(objAds);
}

function GenerateRandomAds2x1(c, adsIndex, rowIndex) {
    var objAds = aryAdsRandom[adsIndex];
    objAds.CounterId = GetLastAdsId();
    objAds.RenderedRow = rowIndex;

    $("<div />")
        .addClass("l-ads-r2x1")
        .appendTo(c)
        .append('<div id="divAds_Rel' + objAds.CounterId + '" class="relpos"></div>')
        .append('<img id="imgAds' + objAds.CounterId + '" src="' + objAds.Images[0] + '" title="' + objAds.Title + '" class="l-img-ads-r2x1 hand" onload="OnAdsImageLoad(' + objAds.CounterId + ');" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', 1, true);" />')
        .append('<div id="pnlI_Ads' + objAds.CounterId + '" class="l-det-ads-r2x1" style="display: none;">' + objAds.Descr + '</div>')
//        .append('<div id="divAdsbL' + objAds.CounterId + '" class="l-info-ads-r2x1 fLeft"></div>')
//        .append('<div id="divAdsbR' + objAds.CounterId + '" class="l-nav-ads-r2x1 fLeft"></div>')
        .append('<div class="clear"></div>');

//    c = $("#divAdsbL" + objAds.CounterId);

//    // Title.
//    $("<div />")
//        .addClass("l-address")
//        .html(objAds.Title)
//        .appendTo(c);

//    // Short description.
//    $("<div />")
//        .addClass("l-price")
//        .html(objAds.ShortDescr)
//        .appendTo(c);

//    c = $("#divAdsbR" + objAds.CounterId);

//    $("<div />")
//        .attr("id", "divAdsbR_1_" + objAds.CounterId)
//        .addClass("tcenter mt9")
//        .appendTo(c);

//    $("<div />")
//        .attr("id", "divAdsbR_2_" + objAds.CounterId)
//        .addClass("tcenter mt9")
//        .appendTo(c);

//    // Navigation.
//    $("#divAdsbR_1_" + objAds.CounterId)
//        .append('<img src="images/06-left.png" title="Previous Image" style="cursor: pointer;' + (objAds.Images.length == 1 && objAds.Descr == '' ? 'display:none;' : '') + '" onmouseover="this.src=\'images/06-left-h.png\'" onmouseout="this.src=\'images/06-left.png\'" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', -1);" />')
//        .append('<img src="images/06-right.png" title="Next Image" style="cursor: pointer;' + (objAds.Images.length == 1 && objAds.Descr == '' ? 'display:none;' : '') + '" onmouseover="this.src=\'images/06-right-h.png\'" onmouseout="this.src=\'images/06-right.png\'" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', 1);" />');

    $("<div />")
        .attr("id", "pnlF_Ads" + objAds.CounterId)
        .attr("align", "center")
        .attr("valign", "middle")
        .addClass("l-img-ads-r2x1 fadediv-ads-r2x1")
        .append('<img src="images/ajax-loader.gif" title="Image Loader" class="fadediv-ads-r2x1" onclick="OnAdsImageLoaderClick(' + objAds.CounterId + ');" />')
        .appendTo($("#divAds_Rel" + objAds.CounterId));

    if (!HasAdsInAll(objAds.CounterId))
        aryAdsAll.push(objAds);
}

function GenerateRandomAds1x1(c, adsIndex, rowIndex) {
    var objAds = aryAdsRandom[adsIndex];
    objAds.CounterId = GetLastAdsId();
    objAds.RenderedRow = rowIndex;

    $("<div />")
        .addClass("l-ads-r1x1")
        .appendTo(c)
        .append('<div id="divAds_Rel' + objAds.CounterId + '" class="relpos"></div>')
        .append('<img id="imgAds' + objAds.CounterId + '" src="' + objAds.Images[0] + '" title="' + objAds.Title + '" class="l-img-ads-r1x1 hand" onload="OnAdsImageLoad(' + objAds.CounterId + ');" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', 1, true);" />')
        .append('<div id="pnlI_Ads' + objAds.CounterId + '" class="l-det-ads-r1x1" style="display: none;">' + objAds.Descr + '</div>')
        //.append('<div id="divAdsbL' + objAds.CounterId + '" class="l-info-ads-r1x1 fLeft"></div>')
        //.append('<div id="divAdsbR' + objAds.CounterId + '" class="l-nav-ads-r1x1 fLeft"></div>')
        ;

//    c = $("#divAdsbL" + objAds.CounterId);

//    // Title.
//    $("<div />")
//        .addClass("l-address")
//        .html(objAds.Title)
//        .appendTo(c);

//    // Short description.
//    $("<div />")
//        .addClass("l-price")
//        .html(objAds.ShortDescr)
//        .appendTo(c);

//    c = $("#divAdsbR" + objAds.CounterId);

//    $("<div />")
//        .attr("id", "divAdsbR_1_" + objAds.CounterId)
//        .addClass("tcenter mt9")
//        .appendTo(c);

//    $("<div />")
//        .attr("id", "divAdsbR_2_" + objAds.CounterId)
//        .addClass("tcenter mt9")
//        .appendTo(c);

//    // Navigation.
//    $("#divAdsbR_1_" + objAds.CounterId)
//        .append('<img src="images/06-left.png" title="Previous Image" style="cursor: pointer;' + (objAds.Images.length == 1 && objAds.Descr == '' ? 'display:none;' : '') + '" onmouseover="this.src=\'images/06-left-h.png\'" onmouseout="this.src=\'images/06-left.png\'" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', -1);" />')
//        .append('<img src="images/06-right.png" title="Next Image" style="cursor: pointer;' + (objAds.Images.length == 1 && objAds.Descr == '' ? 'display:none;' : '') + '" onmouseover="this.src=\'images/06-right-h.png\'" onmouseout="this.src=\'images/06-right.png\'" onclick="OnClickChangeAdsImage(' + objAds.CounterId + ', 1);" />');

    $("<div />")
        .attr("id", "pnlF_Ads" + objAds.CounterId)
        .attr("align", "center")
        .attr("valign", "middle")
        .addClass("l-img-ads-r1x1 fadediv-ads-r1x1")
        .append('<img src="images/ajax-loader.gif" title="Image Loader" class="fadediv-ads-r1x1" onclick="OnAdsImageLoaderClick(' + objAds.CounterId + ');" />')
        .appendTo($("#divAds_Rel" + objAds.CounterId));

    if (!HasAdsInAll(objAds.CounterId))
        aryAdsAll.push(objAds);
}

function GetNextRandomAdsIndex() {
    if (curAdsRandomIndex > aryAdsRandom.length - 1)
        curAdsRandomIndex = 0;

    var retVal = curAdsRandomIndex;
    curAdsRandomIndex++;

    return retVal;
}

function GetAdsOffset(iRow) {
    var start = 0;

    for (var i = aryNumberOfPropertiesPerRow.length - 1; i >= 0; i--)
        if (aryNumberOfPropertiesPerRow[i] != 2) {
            start = i;
            break;
        }

    return start == 0 ? iRow - start : iRow - start - 1;
}

function CreateListingObjHtmlElements() {
    clearTimeout(timerLoader);

    var numElements = GetMaxIndex();
    if (aryProperties.length < numElements) numElements = aryProperties.length;

    var container = $("#divcontainer");
    if (!container) return;

    var insertAfter = 0;
    try {
        insertAfter = parseInt($("#" + GetPropertyValue('InsertRandomAdsRowsClientId')).val());
    }
    catch (e) {
    }

    var rowContainer;
    var iRow = 0;
    var iCol = 0;
    var propsAtRow = 0;

    var i = 0;
    while (i < numElements) {
        if (aryLoadedRows.has(iRow)) {
            i += aryNumberOfPropertiesPerRow[iRow];
            iRow++;
            continue;
        }

        if (iCol == 0) {
            // Row container.
            $("<div />")
                .attr("id", "divLContainer" + iRow)
                .addClass("l-container")
                .appendTo(container);

            rowContainer = $("#divLContainer" + iRow);
        }

        // Ads.
        if (insertAfter != 0 && iCol == 0 && aryAdsRandom.length > 0 && iRow != 0) {
            if (GetAdsOffset(iRow) >= insertAfter) {
                var nextId = GetNextRandomAdsIndex();
                var objAds = aryAdsRandom[nextId];
                if (objAds.Size == '1x1') {
                    GenerateRandomAds1x1(rowContainer, nextId, iRow);

                    iCol++;
                }
                else {
                    GenerateRandomAds2x1(rowContainer, nextId, iRow);

                    aryNumberOfPropertiesPerRow.push(propsAtRow);
                    aryLoadedRows.push(iRow);
                    iRow++;
                    propsAtRow = 0;

                    continue;
                }
            }
        }

        if (iCol == 0) {
            // First property.
            $("<div />")
                .attr("id", "divLContainer" + iRow + "R1")
                .addClass("l-item fLeft ml5")
                .appendTo(rowContainer);

            aryProperties[i].RenderedRow = iRow;
            propsAtRow++;
            GenerateListingObjHtml($("#divLContainer" + iRow + "R1"), "divLContainer" + iRow + "R1", aryProperties[i]);

            iCol++;
            i++;

            continue;
        }

        // Second property.
        $("<div />")
            .attr("id", "divLContainer" + iRow + "R2")
            .addClass("l-item fLeft ml7")
            .appendTo(rowContainer);

        aryProperties[i].RenderedRow = iRow;
        propsAtRow++;
        GenerateListingObjHtml($("#divLContainer" + iRow + "R2"), "divLContainer" + iRow + "R2", aryProperties[i]);

        // Clear div.
        GetClearDiv().appendTo(rowContainer);

        iCol = 0;
        i++;

        aryNumberOfPropertiesPerRow.push(propsAtRow);
        aryLoadedRows.push(iRow);
        iRow++;
        propsAtRow = 0;
    }

    // We should try to load one more property.
    if (iCol == 1) {
        if (numElements >= aryProperties.length) {
            GetClearDiv().appendTo(rowContainer);
        }
        else {
            SetPropertyValue('NumberOfProperties', GetMaxIndex() + 1);
            SetLoadNextControls();
            i = GetMaxIndex() - 1;

            // Second property.
            $("<div />")
                .attr("id", "divLContainer" + iRow + "R2")
                .addClass("l-item fLeft ml7")
                .appendTo(rowContainer);

            aryProperties[i].RenderedRow = iRow;
            propsAtRow++;
            GenerateListingObjHtml($("#divLContainer" + iRow + "R2"), "divLContainer" + iRow + "R2", aryProperties[i]);

            // Clear div.
            GetClearDiv().appendTo(rowContainer);

            iCol = 0;
            i++;

            aryNumberOfPropertiesPerRow.push(propsAtRow);
            aryLoadedRows.push(iRow);
            iRow++;
            propsAtRow = 0;
        }
    }
}

function GetClearDiv() {
    return $("<div />")
        .addClass("clear");
}

function GenerateListingObjHtml(container, containerId, objProperty) {
    // Relative div.
    $("<div />")
        .attr("id", containerId + "Rel" + objProperty.ListingId)
        .addClass("relpos")
        .appendTo(container);

    // Image.
    container.append("<img id=\"imgI_" + objProperty.ListingId + "\" src=\"" + objProperty.ImageLg + "\" title=\"" + objProperty.Address + "\" class=\"l-img hand\" onload=\"OnPropertyImageLoad(" + objProperty.ListingId + ");\" onerror=\"OnErrorPropertyImageLoad(" + objProperty.ListingId + ");\" onclick=\"OnClickChangeImage(" + objProperty.ListingId + ", 1);\" />");

    // Map.
    $("<div />")
        .attr("id", "pnlM_" + objProperty.ListingId)
        .addClass("l-img")
        .appendTo(container);

    var c = $("#pnlM_" + objProperty.ListingId);
    c.hide();

    // Info panel.
    $("<div />")
        .attr("id", "pnlI_" + objProperty.ListingId)
        .addClass("l-det")
        .appendTo(container);

    c = $("#pnlI_" + objProperty.ListingId);

    // Detail panel.
    $("<div />")
        .attr("id", "pnlIsqft_" + objProperty.ListingId)
        .addClass("fLeft ml10")
        .appendTo(c);

    $("<div />")
        .attr("id", "pnlIbeds_" + objProperty.ListingId)
        .addClass("fLeft ml10")
        .appendTo(c);

    $("<div />")
        .attr("id", "pnlIbaths_" + objProperty.ListingId)
        .addClass("fLeft ml10")
        .appendTo(c);

    $("<div />")
        .attr("id", "pnlIgar_" + objProperty.ListingId)
        .addClass("fLeft ml10")
        .appendTo(c);

    $("<div />")
        .addClass("clear")
        .appendTo(c);

    $("<div />")
        .attr("id", "pnlD_" + objProperty.ListingId)
        .addClass("mt10")
        .html("Detail info loading...")
        .appendTo(c);

    c.hide();

    c = $("#pnlIsqft_" + objProperty.ListingId);

    $("<div />")
        .addClass("l-dettitle")
        .html("SQUARE FEET")
        .appendTo(c);

    $("<div />")
        .attr("id", "lblDSqft_" + objProperty.ListingId)
        .addClass("l-dettext mt3")
        .html("Loading...")
        .appendTo(c);

    c = $("#pnlIbeds_" + objProperty.ListingId);

    $("<div />")
        .addClass("l-dettitle")
        .html("BEDROOMS")
        .appendTo(c);

    $("<div />")
        .attr("id", "lblDBedrooms_" + objProperty.ListingId)
        .addClass("l-dettext mt3")
        .appendTo(c);

    c = $("#pnlIbaths_" + objProperty.ListingId);

    $("<div />")
        .addClass("l-dettitle")
        .html("BATHS")
        .appendTo(c);

    $("<div />")
        .attr("id", "lblDBaths_" + objProperty.ListingId)
        .addClass("l-dettext mt3")
        .appendTo(c);

    c = $("#pnlIgar_" + objProperty.ListingId);

    $("<div />")
        .addClass("l-dettitle")
        .html("GARAGES")
        .appendTo(c);

    $("<div />")
        .attr("id", "lblDGarages_" + objProperty.ListingId)
        .addClass("l-dettext mt3")
        .appendTo(c);

    // Left bottom panel.
    $("<div />")
        .attr("id", containerId + "DL" + objProperty.ListingId)
        .addClass("l-info fLeft")
        .appendTo(container);

    c = $("#" + containerId + "DL" + objProperty.ListingId);

    // Address.
    $("<div />")
        .attr("id", containerId + "DL_Addr" + objProperty.ListingId)
        .addClass("l-address")
        .html(objProperty.Address)
        .appendTo(c);

    // Price.
    $("<div />")
        .attr("id", containerId + "DL_Price" + objProperty.ListingId)
        .addClass("l-price")
        .html(objProperty.Price)
        .appendTo(c);

    // Property info.
    $("<div />")
        .attr("id", containerId + "DL_Second" + objProperty.ListingId)
        .addClass("l-price w265")
        .html(objProperty.ListingInfo)
        .appendTo(c);

    // Right bottom panel (navigation).
    $("<div />")
        .attr("id", containerId + "DR" + objProperty.ListingId)
        .addClass("l-nav fLeft")
        .appendTo(container);

    c = $("#" + containerId + "DR" + objProperty.ListingId);

    $("<div />")
        .attr("id", containerId + "DL_Second_1_" + objProperty.ListingId)
        .addClass("tcenter mt9")
        .appendTo(c);

    $("<div />")
        .attr("id", containerId + "DL_Second_2_" + objProperty.ListingId)
        .addClass("tcenter mt9")
        .appendTo(c);

    // Navigation.
    c = $("#" + containerId + "DL_Second_1_" + objProperty.ListingId);

    c.append("<img id=\"imgLeft_" + objProperty.ListingId + "\" src=\"images/06-left.png\" title=\"Previous Image\" style=\"cursor: pointer;\" onmouseover=\"OnMouseOverPrevImage(" + objProperty.ListingId + ");\" onmouseout=\"OnMouseOutPrevImage(" + objProperty.ListingId + ");\" onclick=\"OnClickChangeImage(" + objProperty.ListingId + ", -1);\" />");
    c.append("<img id=\"imgRight_" + objProperty.ListingId + "\" src=\"images/06-right.png\" title=\"Next Image\" style=\"cursor: pointer;\" onmouseover=\"OnMouseOverNextImage(" + objProperty.ListingId + ");\" onmouseout=\"OnMouseOutNextImage(" + objProperty.ListingId + ");\" onclick=\"OnClickChangeImage(" + objProperty.ListingId + ", 1);\" />");

    c = $("#" + containerId + "DL_Second_2_" + objProperty.ListingId);
    c.append("<a href=\"Detail.aspx?Id=" + objProperty.ListingId + "\" onclick=\"return OnClickLnk(" + objProperty.ListingId + ");\"><img id=\"imgDet_" + objProperty.ListingId + "\" src=\"images/06-det1.png\" title=\"Detail Property Information\" style=\"cursor: pointer;\" onmouseover=\"OnMouseOverDetail(" + objProperty.ListingId + ");\" onmouseout=\"OnMouseOutDetail(" + objProperty.ListingId + ");\" /></a>");

    // Shortlist +/-
    c = $("#" + containerId + "Rel" + objProperty.ListingId);
    c.append("<img id=\"imgS_" + objProperty.ListingId + "\" src=\"" + (objProperty.IsInShortlist ? "images/06s-minus.png" : "images/06s-plus.png") + "\" title=\"Add/Remove Property to/from Favorites\" class=\"relpos2 topindex\" onmouseover=\"OnMouseOverShortlist(" + objProperty.ListingId + ");\" onmouseout=\"OnMouseOutShortlist(" + objProperty.ListingId + ");\" onclick=\"OnClickShortlist(" + objProperty.ListingId + ");\" />");

    // Fade panel during images loading.
    $("<div />")
        .attr("id", "pnlF_" + objProperty.ListingId)
        .attr("align", "center")
        .attr("valign", "middle")
        .addClass("l-img fadediv")
        .appendTo(c);

    c = $("#pnlF_" + objProperty.ListingId);
    c.append("<img src=\"images/ajax-loader.gif\" title=\"Image Loader\" class=\"fadediv\" onclick=\"OnImageLoaderClick(" + objProperty.ListingId + ");\" />");
}

function GetPropertyIdForImagesLoading() {
    var maxIndex = GetMaxIndex();

    var i = 0;
    for (i = 0; i < aryProperties.length; i++) {
        if (!aryProperties[i].IsImagesLoaded)
            return aryProperties[i].ListingId;

        if (i >= maxIndex) break;
    }

    return 0;
}

function GetPropertyIdsForLoading() {
    var retVal = "";
    var maxIndex = GetMaxIndex();

    for (var i = 0; i < aryProperties.length; i++) {
        if (!aryProperties[i].IsImagesLoaded) {
            if (retVal != "") retVal += ",";
            retVal += aryProperties[i].ListingId;
        }

        if (i >= maxIndex) break;
    }

    return retVal;
}

function GetMaxIndex() {
    if (GetPropertyValue('NumberOfProperties') == '') return 0;
    return parseInt(GetPropertyValue('NumberOfProperties'));
}

function GetPropertyIdForInfoLoading() {
    var maxIndex = GetMaxIndex();

    var i = 0;
    for (i = 0; i < aryProperties.length; i++) {
        if (!aryProperties[i].IsInfoLoaded)
            return aryProperties[i].ListingId;

        if (i >= maxIndex) break;
    }

    return 0;
}

function LoadPropertyDetails() {
    var ids = GetPropertyIdsForLoading();
    if (ids != "") {
        // Has some properties to load detail info.
        SetPropertyValue('IsLoadingData', 1);

        totalItems++;
        SetProgress('Loading detail info /' + totalItems);
        DG2WebService.ListingGetInfoByIds(ids, OnListingGetInfoByIds);
    }
    else {
        SetPropertyValue('IsLoadingData', 0);
        ClearProgress();

        if (GetMaxIndex() < aryProperties.length)
            StartPolling();

        // Position to last selected property.
        OpenLastSelectedProperty();
    }
}

function GetArrayIndexOfProperty(listingId) {
    for (var i = 0; i < aryProperties.length; i++) {
        if (aryProperties[i].ListingId == listingId)
            return i;
    }
    return -1;
}

function OnListingGetImagesByID2(result) {
    for (var i = 0; i < result.length; i++) {
        var index = GetArrayIndexOfProperty(result[i].listing_id);
        if (index != -1) {
            aryProperties[index].addImage(result[i].url);
            aryProperties[index].IsImagesLoaded = true;
        }
    }

    ClearProgress();
    LoadPropertyDetails();
}

function OnListingGetInfoByIds(result) {
    for (var i = 0; i < result.length; i++) {
        var index = GetArrayIndexOfProperty(result[i].listing_id);
        if (index != -1) {
            var objProperty = aryProperties[index];

            objProperty.addImagesAsStr(result[i].images);
            objProperty.IsImagesLoaded = true;

            objProperty.setDetailInfo(result[i]);
            objProperty.IsInfoLoaded = true;

            SetProgress('Detail info loaded #' + result[i].listing_id);
            UpdateDetailInfoControls(objProperty);
        }
    }

    ClearProgress();
    LoadPropertyDetails();
}

function UpdateDetailInfoControls(objProperty) {
    var elem = $("#lblDBedrooms_" + objProperty.ListingId);
    if (elem) elem.text(objProperty.BedroomsNo);
    elem = $("#pnlIbeds_" + objProperty.ListingId);
    if (elem) {
        if (objProperty.BedroomsNo == "") elem.hide();
        else elem.show();
    }

    elem = $("#lblDBaths_" + objProperty.ListingId);
    if (elem) elem.text(objProperty.BathroomsNo);
    elem = $("#pnlIbaths_" + objProperty.ListingId);
    if (elem) {
        if (objProperty.BathroomsNo == "") elem.hide();
        else elem.show();
    }

    elem = $("#lblDGarages_" + objProperty.ListingId);
    if (elem) elem.text(objProperty.GaragesNo);
    elem = $("#pnlIgar_" + objProperty.ListingId);
    if (elem) {
        if (objProperty.GaragesNo == "") elem.hide();
        else elem.show();
    }

    elem = $("#lblDSqft_" + objProperty.ListingId);
    if (elem) elem.text(trim(objProperty.Sqft + " " + objProperty.SqftSource));
    elem = $("#pnlIsqft_" + objProperty.ListingId);
    if (elem) {
        if (trim(objProperty.Sqft + " " + objProperty.SqftSource) == "" || objProperty.Sqft == "") elem.hide();
        else elem.show();
    }

    elem = $("#pnlD_" + objProperty.ListingId);
    if (elem) elem.html(objProperty.LongDescription);

//    // Hide images panel if necessary.
//    var imgElem = $("#imgI_" + objProperty.ListingId);
//    if (!imgElem) return;

//    var pnlElem = $("#pnlI_" + objProperty.ListingId);
//    if (!pnlElem) return;

//    var pnlMap = $("#pnlM_" + objProperty.ListingId);
//    if (!pnlMap) return;

//    if (!objProperty.HasWrongInitialImage) {
//        if (!objProperty.hasImages()) {
//            imgElem.hide();
//            if (!objProperty.hasMapCoords()) {
//                pnlMap.hide();
//                pnlElem.show();
//            }
//            else {
//                pnlMap.show();
//                InitSmallMap(objProperty.ListingId);
//                pnlElem.hide();
//            }
//        }
//        else {
//            pnlElem.hide();
//            pnlMap.hide();
//            imgElem.show();
//        }
//    }
//    else {
//    }
}

function GetShortlistIndexOfProperty(listingId) {
    for (var i = 0; i < aryShortList.length; i++) {
        if (aryShortList[i].ListingId == listingId)
            return i;
    }
    return -1;
}

function OnListingGetInfoByID2(result) {
    var index = GetArrayIndexOfProperty(result.listing_id);
    if (index != -1) {
        var objProperty = aryProperties[index];

        objProperty.setDetailInfo(result);
        objProperty.IsInfoLoaded = true;

        var elem = $("#lblDBedrooms_" + objProperty.ListingId);
        if (elem) elem.text(objProperty.BedroomsNo);
        elem = $("#pnlIbeds_" + objProperty.ListingId);
        if (elem) {
            if (objProperty.BedroomsNo == "") elem.hide();
            else elem.show();
        }

        elem = $("#lblDBaths_" + objProperty.ListingId);
        if (elem) elem.text(objProperty.BathroomsNo);
        elem = $("#pnlIbaths_" + objProperty.ListingId);
        if (elem) {
            if (objProperty.BathroomsNo == "") elem.hide();
            else elem.show();
        }

        elem = $("#lblDGarages_" + objProperty.ListingId);
        if (elem) elem.text(objProperty.GaragesNo);
        elem = $("#pnlIgar_" + objProperty.ListingId);
        if (elem) {
            if (objProperty.GaragesNo == "") elem.hide();
            else elem.show();
        }

        elem = $("#lblDSqft_" + objProperty.ListingId);
        if (elem) elem.text(trim(objProperty.Sqft + " " + objProperty.SqftSource));
        elem = $("#pnlIsqft_" + objProperty.ListingId);
        if (elem) {
            if (trim(objProperty.Sqft + " " + objProperty.SqftSource) == "" || objProperty.Sqft == "") elem.hide();
            else elem.show();
        }

        elem = $("#pnlD_" + objProperty.ListingId);
        if (elem) elem.html(objProperty.LongDescription);

        // Hide images panel if necessary.
        var imgElem = $("#imgI_" + objProperty.ListingId);
        if (!imgElem) return;

        var pnlElem = $("#pnlI_" + objProperty.ListingId);
        if (!pnlElem) return;

        var pnlMap = $("#pnlM_" + objProperty.ListingId);
        if (!pnlMap) return;

        if (!objProperty.hasImages()) {
            imgElem.hide();
            if (!objProperty.hasMapCoords()) {
                pnlMap.hide();
                pnlElem.show();
            }
            else {
                pnlMap.show();
                InitSmallMap(objProperty.ListingId);
                pnlElem.hide();
            }
        }
        else {
            pnlElem.hide();
            pnlMap.hide();
            imgElem.show();
        }
    }

    ClearProgress();
    LoadPropertyDetails();
}

function GetCurrentPageMode() {
    var curPageMode = pageMode;
    if (curPageMode == 'Search') curPageMode = hashPrevValues['PageMode'];

    return curPageMode;
}

function OnMouseOverMapResults() {
    var elem = ID(GetPropertyValue('MapResultsClientId'));
    if (!elem) return;

//    if (GetCurrentPageMode() == 'LargeMap') elem.src = 'images/06-show-list-results-on.png';
//    else elem.src = 'images/06-show-map-results-on.png';
    if (GetCurrentPageMode() == 'LargeMap') elem.src = 'images/06-map-results-on.png';
    else elem.src = 'images/06-map-results-on.png';
}

function OnMouseOutMapResults() {
    var elem = ID(GetPropertyValue('MapResultsClientId'));
    if (!elem) return;

    //    if (curPageMode == 'LargeMap') elem.src = 'images/06-show-list-results.png';
    //    else elem.src = 'images/06-show-map-results.png';

    //if (GetCurrentPageMode() == 'LargeMap') elem.src = 'images/06ms-on.png';
    //else elem.src = 'images/06ms.png';
    if (GetCurrentPageMode() == 'LargeMap') elem.src = 'images/06-map-results-on.png';
    else elem.src = 'images/06-map-results.png';
}

function OnMouseOverListResults() {
    var elem = ID(GetPropertyValue('ListResultsClientId'));
    if (!elem) return;

    if (GetCurrentPageMode() == 'Grid') elem.src = 'images/06-list-results-on.png';
    else elem.src = 'images/06-list-results-on.png';
}

function OnMouseOutListResults() {
    var elem = ID(GetPropertyValue('ListResultsClientId'));
    if (!elem) return;

    if (GetCurrentPageMode() == 'Grid') elem.src = 'images/06-list-results-on.png';
    else elem.src = 'images/06-list-results.png';
}

function OnMouseOutShortlist_LeftPanel(listingId) {
    var img = ID("imgS_" + listingId + "_F");
    if (!img) return;

    var bInShortlist = img.src.indexOf("minus") >= 0 ? true : false;

    if (bInShortlist) img.src = "images/06s-minus.png";
    else img.src = "images/06s-plus.png";
}

function OnMouseOverShortlist_LeftPanel(listingId) {
    var img = ID("imgS_" + listingId + "_F");
    if (!img) return;

    var bInShortlist = img.src.indexOf("minus") >= 0 ? true : false;

    if (bInShortlist) img.src = "images/06s-minus-h.png";
    else img.src = "images/06s-plus-h.png";
}

function OnMouseOutShortlist(listingId, bMap, bShortlist) {
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;
    ChangeImage(listingId, "imgS_", aryProperties[index].IsInShortlist ? "images/06s-minus.png" : "images/06s-plus.png", index, bMap, bShortlist);
}

function OnMouseOverShortlist(listingId, bMap, bShortlist) {
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;
    ChangeImage(listingId, "imgS_", aryProperties[index].IsInShortlist ? "images/06s-minus-h.png" : "images/06s-plus-h.png", index, bMap, bShortlist);
}

function OnClickShortlist_LeftPanel(listingId) {
    objShortlistLastDeleted = null;
    objPropertyLastDeleted = null;

    var img = ID("imgS_" + listingId + "_F");
    if (!img) return;

    var bInShortlist = img.src.indexOf("minus") >= 0 ? true : false;
    bInShortlist = !bInShortlist;

    // Save at the db.
    DG2WebService.ShortListSavePropertySimple(GetPropertyValue('SessionId'), listingId);

    // Remove from shortlist.
    var index = GetShortlistIndexOfProperty(listingId);
    if (index != -1) {
        objShortlistLastDeleted = aryShortList[index];
        aryShortList.removeAt(index);
        CreateShortlistHtmlElements();
    }

    if (bInShortlist) {
        SetBottomInfo("Moved to Favorites");
    }
    else {
        if (objShortlistLastDeleted) {
            SetProgress("<span style=\"font-decoration: underline; cursor: pointer; border-bottom: solid 1px yellow;\" onclick=\"OnClickUndoShortlist();\">Click here to undo</span>", true);
        }

        SetBottomInfo("Removed from Favorites");
    }

    if (GetPropertyValue('DetailListingId') != '' && GetPropertyValue('AddToShortlist') != '') {
        if (parseInt(GetControlValue(ID(GetPropertyValue('DetailListingId')))) == listingId) {
            var imgDet = ID(GetPropertyValue('AddToShortlist'));
            if (imgDet) imgDet.src = bInShortlist ? "images/06s-minus.png" : "images/06s-plus.png";
        }
    }

    index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;
    var objProperty = aryProperties[index];

    // Change the property state.
    objProperty.IsInShortlist = bInShortlist;

    // Change image.
    ChangeImage(listingId, "imgS_", "images/06s-plus.png", index, false);
    ChangeImage(listingId, "imgS_", "images/06s-plus.png", index, true);

    if (IsFavoritesMode()) {
        objPropertyLastDeleted = objProperty;
        if (largeMap && objProperty.Overlay) {
            largeMap.removeOverlay(objProperty.Overlay);

            // Center to first property from the shortlist.
            if (pageMode == 'LargeMap' && aryShortList.length > 0) {
                iPos = 0;
                while (iPos < aryShortList.length) {
                    var index_ = GetArrayIndexOfProperty(aryShortList[iPos].ListingId);
                    if (index_ >= 0) {
                        if(aryProperties[index_].IsLargeMapDisplayed) {
                            largeMap.setCenter(new GLatLng(aryProperties[index_].Coord2, aryProperties[index_].Coord1), GetSavedZoom('GriffinLargeMapZoom', 13));
                            break;
                        }
                    }
                    iPos++;
                }
            }
        }
        aryProperties.removeAt(index);

        $("#divcontainer").text("");
        aryLoadedRows.clear();
        aryNumberOfPropertiesPerRow.clear();

        SetLoadNextControls();
        CreateListingObjHtmlElements();
    }
}

function OnClickShortlist(listingId, bMap, bShortlist) {
    objShortlistLastDeleted = null;
    objPropertyLastDeleted = null;

    if (bMap == undefined) bMap = false;
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;

    // Save at the db.
    DG2WebService.ShortListSavePropertySimple(GetPropertyValue('SessionId'), listingId);

    // Change the property state.
    aryProperties[index].IsInShortlist = !aryProperties[index].IsInShortlist;

    // Change image.
    ChangeImage(listingId, "imgS_", aryProperties[index].IsInShortlist ? "images/06s-minus" + (!bMap && !bShortlist ? "-h" : "") + ".png" : "images/06s-plus" + (!bMap && !bShortlist ? "-h" : "") + ".png", index, false);
    ChangeImage(listingId, "imgS_", aryProperties[index].IsInShortlist ? "images/06s-minus" + (bMap ? "-h" : "") + ".png" : "images/06s-plus" + (bMap ? "-h" : "") + ".png", index, true);

    SetBottomInfo(aryProperties[index].IsInShortlist ? "Moved to Favorites" : "Removed from Favorites");

    // Insert property to the shortlist.
    var objProperty = aryProperties[index];
    index = GetShortlistIndexOfProperty(listingId);
    if (objProperty.IsInShortlist) {
        if (index == -1) aryShortList.push(new PropertyObj(objProperty.ListingId, objProperty.Address, objProperty.Price, objProperty.PriceSearch, objProperty.ImageLg, "", "", objProperty.IsGriffin, 0, 0, true));
    }
    else {
        if (index != -1) {
            objShortlistLastDeleted = aryShortList[index];
            aryShortList.removeAt(index);
        }

        if (IsFavoritesMode()) {
            index = GetArrayIndexOfProperty(listingId);
            if (index == -1) return;

            objPropertyLastDeleted = objProperty;
            if (largeMap && objProperty.Overlay) {
                largeMap.removeOverlay(objProperty.Overlay);

                // Center to first property from the shortlist.
                if (pageMode == 'LargeMap' && aryShortList.length > 0) {
                    iPos = 0;
                    while (iPos < aryShortList.length) {
                        var index_ = GetArrayIndexOfProperty(aryShortList[iPos].ListingId);
                        if (index_ >= 0) {
                            if (aryProperties[index_].IsLargeMapDisplayed) {
                                largeMap.setCenter(new GLatLng(aryProperties[index_].Coord2, aryProperties[index_].Coord1), GetSavedZoom('GriffinLargeMapZoom', 13));
                                break;
                            }
                        }
                        iPos++;
                    }
                }
            }
            aryProperties.removeAt(index);

            SetProgress("<span style=\"font-decoration: underline; cursor: pointer; border-bottom: solid 1px yellow;\" onclick=\"OnClickUndoShortlist();\">Click here to undo</span>", true);

            $("#divcontainer").text("");
            aryLoadedRows.clear();
            aryNumberOfPropertiesPerRow.clear();

            SetLoadNextControls();
            CreateListingObjHtmlElements();
        }
    }

    CreateShortlistHtmlElements();
}

function OnClickUndoShortlist() {
    if (!objShortlistLastDeleted) return;

    var listingId = objShortlistLastDeleted.ListingId;
    var index = GetShortlistIndexOfProperty(listingId);
    if (index != -1) return;

    aryShortList.push(objShortlistLastDeleted);

    CreateShortlistHtmlElements();

    // Save at the db.
    DG2WebService.ShortListSavePropertySimple(GetPropertyValue('SessionId'), listingId);

    SetBottomInfo("Moved to Favorites");

    if (IsFavoritesMode()) {
        if (!objPropertyLastDeleted) return;

        objPropertyLastDeleted.IsInShortlist = true;

        if (largeMap && objPropertyLastDeleted.Overlay) largeMap.addOverlay(objPropertyLastDeleted.Overlay);
        aryProperties.push(objPropertyLastDeleted);
        aryProperties.sort(ShortListComparer);

        $("#divcontainer").text("");
        aryLoadedRows.clear();
        aryNumberOfPropertiesPerRow.clear();

        SetLoadNextControls();
        CreateListingObjHtmlElements();
    }
    else {
        var index = GetArrayIndexOfProperty(listingId);
        if (index == -1) return;
        var objProperty = aryProperties[index];

        // Change the property state.
        objProperty.IsInShortlist = true;

        // Change image.
        ChangeImage(listingId, "imgS_", "images/06s-minus.png", index, false);
        ChangeImage(listingId, "imgS_", "images/06s-minus.png", index, true);
    }

    ClearProgress();
}

function OnMouseOverPrevImage(listingId, bMap) {
    ChangeImage(listingId, "imgLeft_", "images/06-left-h.png", undefined, bMap);
}

function OnMouseOutPrevImage(listingId, bMap) {
    ChangeImage(listingId, "imgLeft_", "images/06-left.png", undefined, bMap);
}

function OnMouseOverNextImage(listingId, bMap) {
    ChangeImage(listingId, "imgRight_", "images/06-right-h.png", undefined, bMap);
}

function OnMouseOutNextImage(listingId, bMap) {
    ChangeImage(listingId, "imgRight_", "images/06-right.png", undefined, bMap);
}

function OnMouseOverDetail(listingId, bMap) {
    ChangeImage(listingId, "imgDet_", "images/06-det1-h.png", undefined, bMap);
}

function OnMouseOutDetail(listingId, bMap) {
    ChangeImage(listingId, "imgDet_", "images/06-det1.png", undefined, bMap);
}

function ChangeImage(listingId, prefix, src, index, bMap, bShortlist) {
    if (index == undefined) {
        index = GetArrayIndexOfProperty(listingId);
        if (index == -1) return;
    }

    if (bMap == undefined) bMap = false;
    if (bShortlist == undefined) bShortlist = false;
    var elem = ID(prefix + listingId + (bMap ? "_M" : "") + (bShortlist ? "_F" : ""));
    if (!elem) return;

    elem.src = src;
}

function GetIndexInAdsAll(adsCounterId) {
    for (var i = 0; i < aryAdsAll.length; i++)
        if (aryAdsAll[i].CounterId == adsCounterId)
            return i;

    return -1;
}

function OnClickChangeAdsImage(adsCounterId, plus, skipInfo, manual) {
    if (skipInfo == undefined) skipInfo = false;
    if (manual == undefined) manual = true;

    var adsIndexAll = GetIndexInAdsAll(adsCounterId);
    if (adsIndexAll == -1) return;

    var imgElem = $("#imgAds" + adsCounterId);
    if (!imgElem) return;

    var pnlElem = $("#pnlI_Ads" + adsCounterId);
    if (!pnlElem) return;

    var pnlFade = $("#pnlF_Ads" + adsCounterId);
    if (!pnlFade) return;

    var objAds = aryAdsAll[adsIndexAll];
    if (manual) {
        objAds.LastSwitchTime = 0;

        var redirectUrl = '';
        var iPos = objAds.Images.indexOf(imgElem.attr('src'));
        if (iPos >= 0) redirectUrl = objAds.Urls[iPos];

        if (redirectUrl == '') redirectUrl = objAds.Url;

        if (redirectUrl != '') {
            var newWnd = window.open(redirectUrl);
            newWnd.focus();
        }
    }

    var newPos;

    // Currently is info panel.
    if (objAds.IsInfoDisplayed) {
        newPos = plus > 0 ? 0 : objAds.Images.length - 1;
    }
    else {
        newPos = objAds.Images.indexOf(imgElem.attr('src')) + plus;
        if (newPos >= objAds.Images.length)
            newPos = objAds.Descr == "" || skipInfo ? 0 : -1;
        else 
        {
            if (newPos < 0)
                newPos = objAds.Descr == "" || skipInfo ? objAds.Images.length - 1 : -1;
        }
    }

    if (newPos == -1) {
        // Show Info.
        pnlFade.hide();
        imgElem.hide();
        pnlElem.show();
        objAds.IsInfoDisplayed = true;
    }
    else {
        // Show Images.
        pnlElem.hide();
        pnlFade.show();
        imgElem.show();
        imgElem.attr('src', objAds.Images[newPos]);
        objAds.IsInfoDisplayed = false;
    }

    aryAdsAll[adsIndexAll] = objAds;
}

function OnClickChangeImage(listingId, plus, bMap) {
    if (bMap == undefined) bMap = false;

    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;

    var imgElem = $("#imgI_" + listingId + (bMap ? "_M" : ""));
    if (!imgElem) return;

    var pnlElem = $("#pnlI_" + listingId + (bMap ? "_M" : ""));
    if (!pnlElem) return;

    var pnlMap = null;
    if (!bMap) {
        pnlMap = $("#pnlM_" + listingId);
        if (!pnlMap) return;
    }

    var pnlFade = $("#pnlF_" + listingId + (bMap ? "_M" : ""));
    if (!pnlFade) return;

    var objProperty = aryProperties[index];

    var newPos;

    // Currently is info panel.
    if (objProperty.IsInfoDisplayed) {
        if(plus > 0)
        {
            if (objProperty.hasMapCoords() && !bMap)
                newPos = -2;
            else {
                if (!objProperty.hasImages()) return;
                newPos = plus > 0 ? 0 : objProperty.Images.length - 1;
            }
        }
        else
        {
            if(objProperty.hasImages())
                newPos = plus > 0 ? 0 : objProperty.Images.length - 1;
            else {
                if(!objProperty.hasMapCoords() || bMap) return;
                newPos = -2;
            }
        }
    }
    else
    {
        // Currently is map.
        if (objProperty.IsMapDisplayed && !bMap) {
            if (plus > 0) {
                if (objProperty.hasImages())
                    newPos = plus > 0 ? 0 : objProperty.Images.length - 1;
                else {
                    newPos = -1;
                }
            }
            else {
                newPos = -1;
            }
        }
        // Currently is an image.
        else {
            newPos = objProperty.Images.indexOf(imgElem.attr('src')) + plus;
            if (newPos >= objProperty.Images.length)
                newPos = -1;
            else {
                if (newPos < 0) {
                    if (objProperty.hasMapCoords() && !bMap)
                        newPos = -2;
                    else
                        newPos = -1;
                }
            }
        }
    }

    if (newPos == -1) {
        // Show Info.
        pnlFade.hide();
        imgElem.hide();
        if (pnlMap) pnlMap.hide();
        pnlElem.show();
        objProperty.IsInfoDisplayed = true;
        objProperty.IsMapDisplayed = false;
    }
    else if (newPos == -2) {
        // Show Map.
        pnlFade.hide();
        imgElem.hide();
        pnlElem.hide();
        if (pnlMap) pnlMap.show();
        InitSmallMap(objProperty.ListingId);
        objProperty.IsInfoDisplayed = false;
        objProperty.IsMapDisplayed = true;
    }
    else {
        // Show Images.
        if (pnlMap) pnlMap.hide();
        pnlElem.hide();
        pnlFade.show();
        imgElem.show();
        //imgElem.attr('src', objProperty.Images[newPos]);
        ImgLoad(listingId, plus, bMap, objProperty.Images[newPos]);
        objProperty.IsInfoDisplayed = false;
        objProperty.IsMapDisplayed = false;
    }
}

function ImgLoad(listingId, plus, bMap, src) {
    if (bMap == undefined) bMap = false;

    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;
    var objProperty = aryProperties[index];

    var imgElem = $("#imgI_" + listingId + (bMap ? "_M" : ""));
    if (!imgElem) return;

    var pnlElem = $("#pnlI_" + listingId + (bMap ? "_M" : ""));
    if (!pnlElem) return;

    var pnlMap = null;
    if (!bMap) {
        pnlMap = $("#pnlM_" + listingId);
        if (!pnlMap) return;
    }

    var pnlFade = $("#pnlF_" + listingId + (bMap ? "_M" : ""));
    if (!pnlFade) return;

    var oImg = new Image;
    oImg.onload = function() {
        imgElem.attr('src', src);
    }

    oImg.onerror = function() {
        var newPos = objProperty.Images.indexOf(src) + plus;
        if (newPos >= objProperty.Images.length)
            newPos = -1;
        else {
            if (newPos < 0) {
                if (objProperty.hasMapCoords() && !bMap)
                    newPos = -2;
                else
                    newPos = -1;
            }
        }

        if (newPos == -1) {
            // Show Info.
            pnlFade.hide();
            imgElem.hide();
            if (pnlMap) pnlMap.hide();
            pnlElem.show();
            objProperty.IsInfoDisplayed = true;
            objProperty.IsMapDisplayed = false;
        }
        else if (newPos == -2) {
            // Show Map.
            pnlFade.hide();
            imgElem.hide();
            pnlElem.hide();
            if (pnlMap) pnlMap.show();
            InitSmallMap(objProperty.ListingId);
            objProperty.IsInfoDisplayed = false;
            objProperty.IsMapDisplayed = true;
        }
        else {
            // Show Images.
            if (pnlMap) pnlMap.hide();
            pnlElem.hide();
            pnlFade.show();
            imgElem.show();

            newScr = objProperty.Images[newPos];
            objProperty.removeImageByUrl(src);
            ImgLoad(listingId, plus, bMap, newScr);

            objProperty.IsInfoDisplayed = false;
            objProperty.IsMapDisplayed = false;
        }
    }

    oImg.src = src;
}

function StartPolling() {
    timerLoader = setInterval("Poll()", 250);
}

function Poll() {
    if (document.getElementById&&!document.all) {
        currentY = window.pageYOffset;
        currentX = window.pageXOffset;
    }
    else {
        currentY = document.documentElement.scrollTop;
        currentX = document.documentElement.scrollLeft;
    }

    if (aryProperties.length > 0) {
        // Should load next 20 items.
        if (currentY > GetDocumentHeight() - 1500 && pageMode == 'Grid') {
            LoadNextProperties();
        }
    }
}

function SetLoadNextControls() {
    if (GetPropertyValue('Page') != 'Default') return;

    var numProperties = GetMaxIndex();
    if (aryProperties.length <= numProperties) $("#" + GetPropertyValue('LoadNextClientId')).hide();
    else $("#" + GetPropertyValue('LoadNextClientId')).show();

    var btnPrint = null;
    if (GetPropertyValue('PrintClientId') != '') btnPrint = $("#" + GetPropertyValue('PrintClientId'));

    if (aryProperties.length != 0) {
        if (aryProperties.length <= numProperties) {
            $("#lblInfo2").html("" + aryProperties.length + "" + (aryProperties.length == MaxPropertiesToDisplay ? "+" : "") + " " + (aryProperties.length == 1 ? "Property" : "Properties"));
        }
        else {
            $("#lblInfo2").html("" + numProperties + " of " + aryProperties.length + "" + (aryProperties.length == MaxPropertiesToDisplay ? "+" : "") + " " + (numProperties == 1 ? "Property" : "Properties"));
        }

        if (btnPrint) btnPrint.show();
    }
    else {
        $("#lblInfo2").html("No Properties Found");
        if (btnPrint) btnPrint.hide();
    }
}

function LoadNextProperties() {
    var numElements = GetMaxIndex();
    if (numElements >= aryProperties.length) return;

    SetPropertyValue('NumberOfProperties', GetMaxIndex() + NumberOfPropertiesInStep);
    SetLoadNextControls();

    SetBottomInfo('Loading next ' + NumberOfPropertiesInStep + ' properties');
    CreateListingObjHtmlElements();
    MapProperties();
    LoadPropertyDetails();
}

function GetDocumentHeight() {
    if (document.body.scrollHeight) return document.body.scrollHeight;
    return document.documentElement.offsetHeight;
};

function ClearLoadNext() {
    $("#lblInfo2").html("");
}

function ClearQuickSearch() {
    // Address
    val = GetControlValue(ID(GetPropertyValue('SAddressClientId')));
    if (val.toUpperCase() != 'SPECIFIC ADDRESS' && val.toUpperCase() != 'ADDRESS') {
        ID(GetPropertyValue('SAddressClientId')).value = 'Specific Address';
        FadeSddl('SAddress', 'Specific Address', 'Address');
    }

    // City.
    val = GetControlValue(ID(GetPropertyValue('SCitiesClientId')));
    if (val.toUpperCase() != 'DALLAS') {
        $("#" + GetPropertyValue('SCitiesClientId')).selectOptions('Dallas');
        HighlightSddl('SCities', 'All Cities');
    }

    // Price 1.
    val = GetControlValue(ID(GetPropertyValue('SPrices1ClientId')));
    val = parseFloat(val);
    if (val != 0) {
        ID(GetPropertyValue('SPrices1ClientId')).options[0].selected = true;
        FadeSddl('SPrices1', 'Your low price', '0');
    }

    // Price 2.
    val = GetControlValue(ID(GetPropertyValue('SPrices2ClientId')));
    val = parseFloat(val);
    if (val != 0) {
        ID(GetPropertyValue('SPrices2ClientId')).options[0].selected = true;
        FadeSddl('SPrices2', 'Your high price', '0');
    }

    // Area.
    val = GetControlValue(ID(GetPropertyValue('SAreasClientId')));
    if (val.toUpperCase() != 'CHOOSE AREA') {
        $("#" + GetPropertyValue('SAreasClientId')).selectOptions('Choose Area');
        FadeSddl('SAreas', 'Choose Area');
    }

    // Type.
    val = GetControlValue(ID(GetPropertyValue('STypesClientId')));
    if (('' + val).toUpperCase() != '0') {
        ID(GetPropertyValue('STypesClientId')).options[0].selected = true;
        FadeSddl('STypes', '0');
    }

    // Style.
    val = GetControlValue(ID(GetPropertyValue('SStylesClientId')));
    if (('' + val).toUpperCase() != '0') {
        ID(GetPropertyValue('SStylesClientId')).options[0].selected = true;
        FadeSddl('SStyles', '0');
    }

//////    $("#" + GetPropertyValue('ClearSearchClientId')).hide();
    OnChangeSTypes(true);
}

function ResetNumberOfPropertiesToLoad() {
    SetPropertyValue('NumberOfProperties', InitialNumberOfProperties);
}

function ResetLeftButtonsStyle(btnHighClientId) {
    if (btnHighClientId == undefined) btnHighClientId = '';

    var btn = $("#" + GetPropertyValue('FeaturedPropertiesClientId'));
    btn.removeClass('btn-highlighted');
    if (!btn.hasClass('btn-gray')) btn.addClass('btn-gray');

    btn = $("#" + GetPropertyValue('NewListingsClientId'));
    btn.removeClass('btn-highlighted');
    if (!btn.hasClass('btn-gray')) btn.addClass('btn-gray');

    btn = $("#" + GetPropertyValue('DGListingsClientId'));
    btn.removeClass('btn-highlighted');
    if (!btn.hasClass('btn-gray')) btn.addClass('btn-gray');

    btn = $("#" + GetPropertyValue('OpenHousesClientId'));
    btn.removeClass('btn-highlighted');
    if (!btn.hasClass('btn-gray')) btn.addClass('btn-gray');

    btn = $("#" + GetPropertyValue('ModernHousesClientId'));
    btn.removeClass('btn-highlighted');
    if (!btn.hasClass('btn-gray')) btn.addClass('btn-gray');

    btn = $("#" + GetPropertyValue('DetailedSearchClientId'));
    btn.removeClass('btn-highlighted');
    if (!btn.hasClass('btn-gray')) btn.addClass('btn-gray');

    if (btnHighClientId != '') {
        $("#" + GetPropertyValue(btnHighClientId)).removeClass('btn-gray');
        $("#" + GetPropertyValue(btnHighClientId)).addClass('btn-highlighted');
    }
}

function OnClickFeaturedProperties() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 0);
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle('FeaturedPropertiesClientId');
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickDGListings() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 6);
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle('DGListingsClientId');
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickModernHouses() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 7);
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle('ModernHousesClientId');
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickOpenHouses() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 1);
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle('OpenHousesClientId');
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickNewListings() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 2);
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle('NewListingsClientId');
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickQuickSearch() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        SetPropertyValue('TypeId', 3);
        SetPropertyValue('Filter', GetFilterExpression(true));
        SetPropertyValue('MLSNumbers', '');
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle();
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickSearch() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 5);
        SetPropertyValue('Filter', GetFilterExpression(false));
        SetPropertyValue('MLSNumbers', GetMLSNumbers());
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle();
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickShowFavorites() {
    if (GetPropertyValue('Page') == 'Default') {
        //if (pageMode == 'Search') pageMode = GetCurrentPageMode();
        pageMode = 'Grid';
        SetMapSwitchImages();
        ResetNumberOfPropertiesToLoad();

        ClearLoadNext();
        ClearQuickSearch();
        SetPropertyValue('TypeId', 4);
        ShowLoadingPanel();
        PageInit();

        OnClickLnk();
        ResetLeftButtonsStyle();
        $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickDetailedSearch() {
    if (GetPropertyValue('Page') == 'Default') {
        $("#divLoading").hide();
        $("#divLargeMapContainer").hide();
        $("#divcontainer").hide();
        $("#divInfoPanel").hide();
        $("#divSearch").show();
        if (pageMode != 'Search') hashPrevValues['PageMode'] = pageMode;
        pageMode = 'Search';

        ResetLeftButtonsStyle('DetailedSearchClientId');

        return false;
    }

    return true;
}

function OnClickMapResults() {
    if (GetPropertyValue('Page') == 'Default') {
        $("#divSearch").hide();
        $("#divInfoPanel").show();

        // Switch current view.
        if (GetCurrentPageMode() == 'Grid') {
            $("#divcontainer").hide();
            $("#divLargeMapContainer").show();
            pageMode = 'LargeMap';
            InitLargeMap();
            MapProperties();
        }
        else {
            $("#divLargeMapContainer").hide();
            $("#divcontainer").show();
            pageMode = 'Grid';
        }

        //    // Change image MAP/LIST RESULTS.
        //    var elem = ID(GetPropertyValue('MapSearchClientId'));
        //    if (!elem) return;

        ////    if (GetCurrentPageMode() == 'LargeMap') elem.src = 'images/06-show-list-results.png';
        ////    else elem.src = 'images/06-show-map-results.png';
        //    if (GetCurrentPageMode() == 'LargeMap') elem.src = 'images/06ms-on.png';
        //    else elem.src = 'images/06ms.png';

//        // Change images LIST RESULTS and MAP RESULTS
//        var elem1 = ID(GetPropertyValue('MapResultsClientId'));
//        if (!elem1) return;

//        var elem2 = ID(GetPropertyValue('ListResultsClientId'));
//        if (!elem2) return;

//        if (GetCurrentPageMode() == 'LargeMap') {
//            elem1.src = 'images/06-map-results-on.png';
//            elem2.src = 'images/06-list-results.png';
//        }
//        else {
//            elem1.src = 'images/06-map-results.png';
//            elem2.src = 'images/06-list-results-on.png';
//        }

        if (GetCurrentPageMode() == 'LargeMap') $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW LIST');
        else $("#" + GetPropertyValue('SwitchMapClientId')).text('SHOW MAP');

        return false;
    }

    return true;
}

function OnClickLoadNext() {
    LoadNextProperties();

    return false;
}

function ShowLoadingPanel() {
    if (timerInfo) clearTimeout(timerInfo);
    if (timerLoader) clearTimeout(timerLoader);

    $("#divcontainer").text('');
    $("#divcontainer").hide();
    $("#divSearch").hide();
    $("#divLargeMapContainer").hide();
    $("#divLoading").show();
    $("#divInfoPanel").show();
}

function GetControlValue(obj) {
    if (!obj) return '';

    if (obj.tagName.toUpperCase() == 'INPUT') {
        if (obj.type == 'text')
            return obj.value;

        if (obj.type == 'radio') {
            var pos = obj.id.lastIndexOf('_');
            var radioIndex = obj.id.substr(pos + 1);

            if (obj.checked) {
                return radioIndex;
            }
            else {
                var idPart = obj.id.substr(0, pos + 1);
                var i = 0;
                while (1 == 1) {
                    var elem = window.document.getElementById(idPart + i);
                    if (elem) {
                        if (elem.checked)
                            return i;
                    }
                    else
                        break;

                    i++;
                }
            }
        }

        if (obj.type == 'checkbox') {
            var selIndexes = '';

            var pos = obj.id.lastIndexOf('_');
            var idPart = obj.id.substr(0, pos + 1);
            var i = 0;
            while (1 == 1) {
                var elem = ID(idPart + i);
                if (elem) {
                    if (elem.checked)
                        selIndexes += (selIndexes == '' ? '' : ',') + i;
                }
                else
                    break;

                i++;
            }

            return selIndexes;
        }
    }

    if (obj.tagName.toUpperCase() == 'SELECT') {
        return obj.options[obj.selectedIndex].value;
    }

    if (obj.tagName.toUpperCase() == 'TEXTAREA') return obj.value;

    return '';
}

function GetMLSNumbers() {
    var val = GetControlValue(ID(GetPropertyValue('DetSearchMLSClientId')));
    return val.replace(' ', '');
}

function GetFilterExpression(bQuickSearch) {
    var strRet = ''
    var bHasFilter = false;
    var val;

    // Address
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('SAddressClientId')));
    else val = GetControlValue(ID(GetPropertyValue('DetSearchAddressClientId')));
    if (val.toUpperCase() != 'SPECIFIC ADDRESS' && val.toUpperCase() != 'ADDRESS') {
        strRet = val;
        bHasFilter = true;
    }
    
    // Zip code.
    strRet += ';ZIP='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchZipCodeClientId')));
        if (val.toUpperCase() != 'ZIP CODE' && val.toUpperCase() != 'ZIP') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // City.
    strRet += ';CITY='
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('SCitiesClientId')));
    else val = GetControlValue(ID(GetPropertyValue('DetSearchCitiesClientId')));
    if (val.toUpperCase() != 'ALL CITIES') {
        strRet += val;
        bHasFilter = true;
    }

    // Price range.
    strRet += ';PRICE='
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('SPrices1ClientId')));
    else val = GetControlValue(ID(GetPropertyValue('DetSearchPrices1ClientId')));
    val = parseFloat(val);
    if (val != 0) {
        strRet += val;
        bHasFilter = true;
    }
    strRet += ";"
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('SPrices2ClientId')));
    else val = GetControlValue(ID(GetPropertyValue('DetSearchPrices2ClientId')));
    val = parseFloat(val);
    if (val != 0) {
        strRet += val;
        bHasFilter = true;
    }

    // Agent.
    strRet += ';AGENT='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchAgentClientId')));
        if (val.toUpperCase() != 'AGENT NAME' && val.toUpperCase() != 'AGENT') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Elementary school.
    strRet += ';SCH_ELEM='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchElementrySchoolClientId')));
        if (val.toUpperCase() != 'CHOOSE ELEMENTRY SCHOOL' && val.toUpperCase() != 'ELEMENTRY SCHOOL') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Middle school.
    strRet += ';SCH_MIDDLE='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchMiddleSchoolClientId')));
        if (val.toUpperCase() != 'CHOOSE MIDDLE SCHOOL' && val.toUpperCase() != 'MIDDLE SCHOOL') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // High school.
    strRet += ';SCH_HIGH='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchHighSchoolClientId')));
        if (val.toUpperCase() != 'CHOOSE HIGH SCHOOL' && val.toUpperCase() != 'HIGH SCHOOL') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Baths.
    strRet += ';BATHS='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchBathroomsClientId')));
        if (val.toUpperCase() != 'CHOOSE BATHROOMS NUMBER' && val.toUpperCase() != 'BATHROOMS NUMBER' && val.toUpperCase() != 'BATHROOMS') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Bedrooms.
    strRet += ';BEDS='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchBedroomsClientId')));
        if (val.toUpperCase() != 'CHOOSE BEDROOMS NUMBER' && val.toUpperCase() != 'BEDROOMS NUMBER' && val.toUpperCase() != 'BEDROOMS') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Garages.
    strRet += ';GARAGES='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchGaragesClientId')));
        if (val.toUpperCase() != 'CHOOSE GARAGES NUMBER' && val.toUpperCase() != 'GARAGES NUMBER' && val.toUpperCase() != 'GARAGES') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Number of Stories.
    strRet += ';STORIES='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchStoriesClientId')));
        if (val.toUpperCase() != 'CHOOSE STORIES NUMBER' && val.toUpperCase() != 'STORIES NUMBER' && val.toUpperCase() != 'STORIES') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Acres.
    strRet += ';ACRES='
    if (!bQuickSearch) {
        val = GetControlValue(ID(GetPropertyValue('DetSearchAcresClientId')));
        if (val.toUpperCase() != 'CHOOSE ACRES' && val.toUpperCase() != 'ACRES') {
            strRet += val;
            bHasFilter = true;
        }
    }

    // Area.
    strRet += ';AREA='
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('SAreasClientId')));
    else val = GetControlValue(ID(GetPropertyValue('DetSearchAreasClientId')));
    if (val.toUpperCase() != 'CHOOSE AREA') {
        strRet += val;
        bHasFilter = true;
    }

    // Type.
    strRet += ';TYPE='
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('STypesClientId')));
    else val = GetDetSearchType();
    if (('' + val).toUpperCase() != '0') {
        strRet += val;
        bHasFilter = true;
    }

    // Style.
    strRet += ';STYLE='
    if (bQuickSearch) val = GetControlValue(ID(GetPropertyValue('SStylesClientId')));
    else val = GetDetSearchStyle();
    if (('' + val).toUpperCase() != '0') {
        strRet += val;
        bHasFilter = true;
    }

    if (!bHasFilter)
        strRet = '';

    return strRet;
}

function OnPropertyImageLoad(listingId, bMap) {
    if (bMap == undefined) bMap = false;
    $("#pnlF_" + listingId + (bMap ? "_M" : "")).hide();

    if (ID("imgI_" + listingId + (bMap ? "_M" : "")))
        if (ID("imgI_" + listingId + (bMap ? "_M" : "")).src == EmptyImageUrl)
            HandleWrongImage(listingId, bMap, true);
}

function OnAdsImageLoad(adsCounterId) {
    $("#pnlF_Ads" + adsCounterId).hide();
}

function HandleWrongImage(listingId, bMap, bSuccess) {
    if (bMap == undefined) bMap = false;

    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;
    var objProperty = aryProperties[index];

    var pnlFade = $("#pnlF_" + objProperty.ListingId + (bMap ? "_M" : ""));
    if (!pnlFade) return;

    var imgElem = $("#imgI_" + objProperty.ListingId + (bMap ? "_M" : ""));
    if (!imgElem) return;

    var pnlElem = $("#pnlI_" + objProperty.ListingId + (bMap ? "_M" : ""));
    if (!pnlElem) return;

    var pnlMap = $("#pnlM_" + objProperty.ListingId);
    if (!pnlMap) return;

    if (!objProperty.IsImagesLoaded) {
        // Initial loading, mark the property, we will check other images as soon as they will be available.
        objProperty.HasWrongInitialImage = true;

        // Show map if it has geocodes, else show empty image.
        if (objProperty.hasMapCoords()) {
            pnlFade.hide();
            pnlMap.show();
            InitSmallMap(objProperty.ListingId);
            imgElem.hide();

            objProperty.IsInfoDisplayed = false;
            objProperty.IsMapDisplayed = true;
        }
        else {
            if (!bSuccess) ID("imgI_" + objProperty.ListingId + (bMap ? "_M" : "")).src = EmptyImageUrl;

            objProperty.IsInfoDisplayed = false;
            objProperty.IsMapDisplayed = false;
        }
    }
    else {
        if (objProperty.hasMapCoords()) {
            pnlFade.hide();
            pnlMap.show();
            InitSmallMap(objProperty.ListingId);
            imgElem.hide();

            objProperty.IsInfoDisplayed = false;
            objProperty.IsMapDisplayed = true;
        }
        else {
            pnlFade.hide();
            pnlMap.hide();
            pnlElem.show();
            imgElem.hide();

            objProperty.IsInfoDisplayed = true;
            objProperty.IsMapDisplayed = false;
        }
    }
}

function OnErrorPropertyImageLoad(listingId, bMap) {
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;

    if (ID("imgI_" + listingId + (bMap ? "_M" : "")))
        aryProperties[index].removeImageByUrl(ID("imgI_" + listingId + (bMap ? "_M" : "")).src);

    HandleWrongImage(listingId, bMap, false);
}

function OnImageLoaderClick(listingId, bMap) {
    if (bMap == undefined) bMap = false;
    $("#pnlF_" + listingId + (bMap ? "_M" : "")).hide();
}

function OnAdsImageLoaderClick(adsCounterId) {
    $("#pnlF_Ads" + adsCounterId).hide();
}

function InitIcons() {
    iconGriffin = new GIcon();
    iconGriffin.image = "http://davidgriffin.com/images/dgGoogleIcon.png";
    iconGriffin.shadow = "http://www.google.com/mapfiles/shadow50.png";
    iconGriffin.iconSize = new GSize(35, 35);
    iconGriffin.shadowSize = new GSize(22, 20);
    iconGriffin.iconAnchor = new GPoint(6, 20);
    iconGriffin.infoWindowAnchor = new GPoint(5, 1);

    iconMLS = new GIcon();
    iconMLS.image = "http://davidgriffin.com/images/mlsGoogleIcon.png";
    iconMLS.shadow = "http://www.google.com/mapfiles/shadow50.png";
    iconMLS.iconSize = new GSize(35, 35);
    iconMLS.shadowSize = new GSize(22, 20);
    iconMLS.iconAnchor = new GPoint(6, 20);
    iconMLS.infoWindowAnchor = new GPoint(5, 1);
}

function InitGMaps() {
    isMapCompatible = GBrowserIsCompatible();
    if (!isMapCompatible) return;
}

function GetSavedZoom(id, defaultZoomLevel) {
    var savedZoom = defaultZoomLevel;
    if (GetCookie(id) != null && isFinite(GetCookie(id)))
        savedZoom = parseInt(GetCookie(id));

    return savedZoom;
}

function GetSavedMapType(id) {
    curType = G_NORMAL_MAP;

    savedType = GetCookie(id);
    if (savedType != null) {
        if (savedType == 'G_SATELLITE_MAP') curType = G_SATELLITE_MAP;
        if (savedType == 'G_NORMAL_MAP') return curType = G_NORMAL_MAP;
        if (savedType == 'G_HYBRID_MAP') return curType = G_HYBRID_MAP;
    }

    return curType;
}

function InitSmallMap(listingId) {
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;

    var pnlMap = ID("pnlM_" + listingId);
    if (!pnlMap) return;

    var objProperty = aryProperties[index];
    if (hashMaps.containsKey(listingId)) return;

    var propCoord = new GLatLng(objProperty.Coord2, objProperty.Coord1);

    var smallMap = new GMap2(pnlMap);
    smallMap.addControl(new GSmallMapControl());
    smallMap.addControl(new GMapTypeControl());

    smallMap.setCenter(propCoord, GetSavedZoom('GriffinSmallMapZoom', 16));
    smallMap.setMapType(GetSavedMapType('GriffinSmallMapType'));
    smallMap.setZoom(GetSavedZoom('GriffinSmallMapZoom', 16));

    GEvent.addListener(smallMap, "zoomend", function(oldLevel, newLevel) {
        SetCookie('GriffinSmallMapZoom', newLevel);
        SetCookie('GriffinSmallMapType', GetCurrentMapType(smallMap));
    });
    GEvent.addListener(smallMap, "maptypechanged", function() {
        SetCookie('GriffinSmallMapZoom', smallMap.getZoom());
        SetCookie('GriffinSmallMapType', GetCurrentMapType(smallMap));
    });

    var newOverlay = new GMarker(propCoord, objProperty.IsGriffin ? iconGriffin : iconMLS);
    smallMap.addOverlay(newOverlay);

    hashMaps.put(listingId, smallMap);
}

function InitLargeMap() {
    var pnlMap = ID("divLargeMap");
    if (!pnlMap) return;
    //if (largeMap) return;

    largeMap = new GMap2(pnlMap);
    largeMap.addControl(new GLargeMapControl());
    largeMap.addControl(new GMapTypeControl());

    largeMap.setCenter(new GLatLng(32.805, -96.820), GetSavedZoom('GriffinLargeMapZoom', 13));
    largeMap.setMapType(GetSavedMapType('GriffinLargeMapType'));
    largeMap.setZoom(GetSavedZoom('GriffinLargeMapZoom', 13));

    GEvent.addListener(largeMap, "click", OnLargeMapClick);
    GEvent.addListener(largeMap, "zoomend", OnLargeMapZoomend);
    GEvent.addListener(largeMap, "maptypechanged", OnLargeMapTypeChanged);
}

function GetCurrentMapType(m) {
    var curType = m.getCurrentMapType();

    if (curType == G_SATELLITE_MAP) return 'G_SATELLITE_MAP';
    if (curType == G_NORMAL_MAP) return 'G_NORMAL_MAP';
    if (curType == G_HYBRID_MAP) return 'G_HYBRID_MAP';

    return G_NORMAL_MAP;
}

function OnLargeMapZoomend(oldLevel, newLevel) {
    SetCookie('GriffinLargeMapZoom', newLevel);
    SetCookie('GriffinLargeMapType', GetCurrentMapType(largeMap));
}

function OnLargeMapTypeChanged() {
    SetCookie('GriffinLargeMapZoom', largeMap.getZoom());
    SetCookie('GriffinLargeMapType', GetCurrentMapType(largeMap));
}

function MapProperties() {
    if (pageMode != "LargeMap") return;
    if (!largeMap) InitLargeMap();

    bMoveToPoint = true;
    bByZip = false;
    var foundPoint = null;

    var numElements = GetMaxIndex();
    if (aryProperties.length < numElements) numElements = aryProperties.length;

    var objProperty;
    for (var i = 0; i < numElements; i++) {
        objProperty = aryProperties[i];
        if (!objProperty.hasMapCoords()) continue;
//        if (objProperty.IsLargeMapDisplayed) {
//            bMoveToPoint = false;
//            continue;
//        }

        if (!bByZip) {
            if (objProperty.ZipCode.substr(0, 2) == '75') {
                foundPoint = new GLatLng(objProperty.Coord2, objProperty.Coord1);
                bByZip = true;
            }
            else {
                if (!foundPoint) foundPoint = new GLatLng(objProperty.Coord2, objProperty.Coord1);
            }
        }

        var newOverlay = new GMarker(new GLatLng(objProperty.Coord2, objProperty.Coord1), objProperty.IsGriffin ? iconGriffin : iconMLS);
        largeMap.addOverlay(newOverlay);
        objProperty.setOverlay(newOverlay);

        objProperty.IsLargeMapDisplayed = true;
    }

    //if (bMoveToPoint && foundPoint && largeMap)
    //    largeMap.setCenter(foundPoint);
    if (foundPoint && largeMap)
        largeMap.setCenter(foundPoint, GetSavedZoom('GriffinLargeMapZoom', 13));
}

function OpenLastSelectedProperty() {
    // Open last selected property overlay.
    if (GetPropertyValue('LastSelectedListingId') == 0) return;

    var indexOfProperty = GetArrayIndexOfProperty(GetPropertyValue('LastSelectedListingId'));
    if (indexOfProperty == -1) return;

    if (pageMode == 'LargeMap') {
        objProperty = aryProperties[indexOfProperty];
        if (objProperty.IsLargeMapDisplayed) OpenInfoWindow(objProperty);
    }
    else if (pageMode == 'Grid') {
    var topMargin = 181 + aryProperties[indexOfProperty].RenderedRow * (318 + 8);
        if (objCurAdsHeader != null)
            topMargin += parseInt($("#divAds" + objCurAdsHeader.CounterId).height()) + 8;

        window.scrollTo(0, topMargin);
    }

    // Reset last selected property.
    hashPrevValues['LastSelectedListingId'] = GetPropertyValue('LastSelectedListingId');
    SetPropertyValue('LastSelectedListingId', 0);
}

function GetArrayIndexOfPropertyByCoords(coord1, coord2) {
    for (var i = 0; i < aryProperties.length; i++) {
        if (aryProperties[i].Coord1 == coord1 && aryProperties[i].Coord2 == coord2)
            return i;
    }
    return -1;
}

function OnLargeMapClick(overlay, point) {
    if (!overlay) return;

    var index = GetArrayIndexOfPropertyByCoords(overlay.getPoint().lng(), overlay.getPoint().lat());
    if (index == -1) return;

    OpenInfoWindow(aryProperties[index], overlay);
}

function HasPropertiesAtMap(listingId, arrow) {
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return false;

    var numElements = GetMaxIndex();
    if (aryProperties.length < numElements) numElements = aryProperties.length;

    var newIndex = index + arrow;
    if (newIndex < 0 || newIndex > numElements - 1) return false;

    while (!aryProperties[newIndex].hasMapCoords()) {
        newIndex += arrow;
        if (newIndex < 0 || newIndex > numElements - 1) return false;
    }

    return true;
}

function OpenInfoWindow(objProperty, overlay) {
    if (overlay == undefined) overlay = objProperty.Overlay;

    var bAtLeft = HasPropertiesAtMap(objProperty.ListingId, -1);
    var bAtRight = HasPropertiesAtMap(objProperty.ListingId, 1);
    var bSpace = bAtLeft && bAtRight;

    var bHasImage = objProperty.ImageLg == EmptyImageUrl || !objProperty.hasImages() ? false : true;

    // Save last selected property.
    DG2WebService.SaveCurrentListingId(objProperty.ListingId);

    try {
        var sqft = trim(objProperty.Sqft + " " + objProperty.SqftSource);
        if (objProperty.Sqft == "") sqft = "";

        overlay.openInfoWindowHtml(
            "<div style=\"padding-top: 12px;\">" +
                "<div style=\"width: 360px; height: 320px;\">" +
                    "<div class=\"relpos\">" +
                        "<img id=\"imgS_" + objProperty.ListingId + "_M" + "\" src=\"" + (objProperty.IsInShortlist ? "images/06s-minus.png" : "images/06s-plus.png") + "\" title=\"Add/Remove Property to/from Favorites\" class=\"relpos2 topindex\" onmouseover=\"OnMouseOverShortlist(" + objProperty.ListingId + ", true);\" onmouseout=\"OnMouseOutShortlist(" + objProperty.ListingId + ", true);\" onclick=\"OnClickShortlist(" + objProperty.ListingId + ", true);\" />" +
                        "<div id=\"pnlF_" + objProperty.ListingId + "_M" + "\" class=\"l-img fadediv\" style=\"display: none;\">" +
                            "<img src=\"images/ajax-loader.gif\" title=\"Image Loader\" class=\"fadediv\" onclick=\"OnImageLoaderClick(" + objProperty.ListingId + ", true);\" />" +
                        "</div>" +
                        "<div class=\"map-prop-nav\">" +
                            "<span id=\"lblMapPrevProp\" title=\"Open previous property\" style=\"cursor: pointer;" + (bAtLeft ? "" : "display: none;") + "\" onmouseover=\"this.style.textDecoration = 'underline';\" onmouseout=\"this.style.textDecoration = 'none';\" onclick=\"OnClickMapPrevNext(" + objProperty.ListingId + ", -1);\">PREVIOUS</span>" +
                            "<span id=\"lblMapSpace\" style=\"" + (bSpace ? "" : "display: none;") + "\">&nbsp;/&nbsp;</span>" +
                            "<span id=\"lblMapNextProp\" title=\"Open next property\" style=\"cursor: pointer;" + (bAtRight ? "" : "display: none;") + "\" onmouseover=\"this.style.textDecoration = 'underline';\" onmouseout=\"this.style.textDecoration = 'none';\" onclick=\"OnClickMapPrevNext(" + objProperty.ListingId + ", 1);\">NEXT</span>" + 
                        "</div>" + 
                    "</div>" +
                    "<img id=\"imgI_" + objProperty.ListingId + "_M" + "\" src=\"" + objProperty.ImageLg + "\" style=\"" + (bHasImage ? "" : "display: none;") + "\" title=\"" + objProperty.Address + "\" class=\"l-img hand\" onload=\"OnPropertyImageLoad(" + objProperty.ListingId + ", true);\" onerror=\"OnErrorPropertyImageLoad(" + objProperty.ListingId + ", true);\" onclick=\"OnClickChangeImage(" + objProperty.ListingId + ", 1, true);\" />" +
                    "<div id=\"pnlI_" + objProperty.ListingId + "_M" + "\" class=\"l-img l-det-map\" style=\"" + (!bHasImage ? "" : "display: none;") + "\">" +
                        "<div id=\"pnlIsqft_" + objProperty.ListingId + "_M" + "\" class=\"fLeft\" " + (sqft == "" ? "style=\"display: none;\"" : "") + ">" +
                            "<div class=\"l-dettitle-map\">SQUARE FEET</div>" +
                            "<div class=\"l-dettext mt3\">" + sqft + "</div>" +
                        "</div>" +
                        "<div id=\"pnlIbeds_" + objProperty.ListingId + "_M" + "\" class=\"fLeft ml10\" " + (objProperty.BedroomsNo == "" ? "style=\"display: none;\"" : "") + ">" +
                            "<div class=\"l-dettitle-map\">BEEDROOMS</div>" +
                            "<div class=\"l-dettext mt3\">" + objProperty.BedroomsNo + "</div>" +
                        "</div>" +
                        "<div id=\"pnlIbaths_" + objProperty.ListingId + "_M" + "\" class=\"fLeft ml7\" " + (objProperty.BathroomsNo == "" ? "style=\"display: none;\"" : "") + ">" +
                            "<div class=\"l-dettitle-map\">BATHS</div>" +
                            "<div class=\"l-dettext mt3\">" + objProperty.BathroomsNo + "</div>" +
                        "</div>" +
                        "<div id=\"pnlIgar_" + objProperty.ListingId + "_M" + "\" class=\"fLeft ml7\" " + (objProperty.GaragesNo == "" ? "style=\"display: none;\"" : "") + ">" +
                            "<div class=\"l-dettitle-map\">GARAGES</div>" +
                            "<div class=\"l-dettext mt3\">" + objProperty.GaragesNo + "</div>" +
                        "</div>" +
                        "<div class=\"clear\"></div>" +
                        "<div class=\"mt10\" style=\"text-align: left;\"><div>" + objProperty.LongDescription + "</div></div>" +
                    "</div>" +
                    "<div class=\"l-info-map fLeft tleft\">" +
                        "<div class=\"l-address-map\">" + objProperty.Address + "</div>" +      // Address.
                        "<div class=\"l-price-map\">" + objProperty.Price + "</div>" +          // Price.
                        "<div class=\"l-price-map\">" + objProperty.ListingInfo + "</div>" +    // Listing Info.
                    "</div>" +
                    "<div class=\"l-nav fLeft\">" +
                        "<div class=\"tcenter mt9\">" +
                            "<img id=\"imgLeft_" + objProperty.ListingId + "_M" + "\" src=\"images/06-left.png\" title=\"Previous Image\" style=\"cursor: pointer;\" onmouseover=\"OnMouseOverPrevImage(" + objProperty.ListingId + ", true);\" onmouseout=\"OnMouseOutPrevImage(" + objProperty.ListingId + ", true);\" onclick=\"OnClickChangeImage(" + objProperty.ListingId + ", -1, true);\" />" +
                            "<img id=\"imgRight_" + objProperty.ListingId + "_M" + "\" src=\"images/06-right.png\" title=\"Next Image\" style=\"cursor: pointer;\" onmouseover=\"OnMouseOverNextImage(" + objProperty.ListingId + ", true);\" onmouseout=\"OnMouseOutNextImage(" + objProperty.ListingId + ", true);\" onclick=\"OnClickChangeImage(" + objProperty.ListingId + ", 1, true);\" />" +
                        "</div>" +
                        "<div class=\"tcenter mt9\">" +
                            "<a href=\"Detail.aspx?Id=" + objProperty.ListingId + "\" onclick=\"return OnClickLnk(" + objProperty.ListingId + ");\"><img id=\"imgDet_" + objProperty.ListingId + "_M" + "\" src=\"images/06-det1.png\" title=\"Detail Property Information\" style=\"cursor: pointer; border: 0px;\" onmouseover=\"OnMouseOverDetail(" + objProperty.ListingId + ", true);\" onmouseout=\"OnMouseOutDetail(" + objProperty.ListingId + ", true);\" /></a>" +
                        "</div>" +
                    "</div>" + 
                "</div>" +
            "</div>"
        );
    } catch (e) {
    }
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function LoadShortlist() {
    DG2WebService.ShortlistGetList2(GetPropertyValue('SessionId'), OnShortlistGetList2);
}

function OnShortlistGetList2(result) {
    aryShortList.clear();

    var i;
    for (i = 0; i < result.length; i++) {
        aryShortList.push(new PropertyObj(result[i].listing_id, result[i].address, result[i].price, result[i].price_search, result[i].image_lg, result[i].listing_info, result[i].zip, result[i].is_Griffin, result[i].coord1, result[i].coord2, result[i].has_shortlist));
    }

    CreateShortlistHtmlElements();
}

function ShortListComparer(a, b) {
    if (a.IsGriffin && !b.IsGriffin) return -1;
    if (!a.IsGriffin && b.IsGriffin) return 1;

    if (a.PriceSearch > b.PriceSearch) return -1;
    if (a.PriceSearch < b.PriceSearch) return 1;

    return 0;
}

function CreateShortlistHtmlElements() {
    var container = $("#divFavorContainer").html('');

    aryShortList.sort(ShortListComparer);

    if (aryShortList.length == 0) $("#divFavour").hide();
    else $("#divFavour").show();

    for (var i = 0; i < aryShortList.length; i++) {
        if (i >= NumberOfTopFavorites) break;

        container.append(
            "<div class=\"relpos\">" +
                "<img id=\"imgS_" + aryShortList[i].ListingId + "_F" + "\" src=\"images/06s-minus.png\" title=\"Remove Property from Favorites\" class=\"relpos-fav topindex\" onmouseover=\"OnMouseOverShortlist_LeftPanel(" + aryShortList[i].ListingId + ");\" onmouseout=\"OnMouseOutShortlist_LeftPanel(" + aryShortList[i].ListingId + ");\" onclick=\"OnClickShortlist_LeftPanel(" + aryShortList[i].ListingId + ");\" />" +
            "</div>"
        );

        container.append(
            "<div>" +
                "<a href=\"Detail.aspx?Id=" + aryShortList[i].ListingId + "\" onclick=\"return OnClickLnk();\"><img src=\"" + aryShortList[i].ImageLg + "\" title=\"" + aryShortList[i].Address + "\" class=\"s-img\" onerror=\"this.src='http://davidgriffin.com/listingimages/PropImage.gif'\" /></a>" +
            "</div>"
        );
    }
}

function HasElementsInHash(hash) {
    for (var item in hash) {
        return true;
    }

    return false;
}

function GetOptions(obj) {
    var hash = new Object();

    for (var i = 0; i < obj.options.length; i++)
        hash[obj.options[i].value] = obj.options[i].text

    return hash;
}

function OnChangeSTypes(bQuickSearch) {
    var clientId = null;
    if (bQuickSearch) clientId = GetPropertyValue('STypesClientId');

    if (!clientId) return;

    var elem = ID(clientId);
    if (!elem) return;

    var cbxPrice1 = $("#" + GetPropertyValue('SPrices1ClientId'));
    var cbxPrice2 = $("#" + GetPropertyValue('SPrices2ClientId'));
    if (!cbxPrice1 || !cbxPrice2) return;

    var selVal = '' + GetControlValue(elem);
    if (selVal == '13' || hashPrevValues['STypes'] == '13') {
        cbxPrice1.removeOption(/./);
        cbxPrice2.removeOption(/./);

        cbxPrice1.addOption(GetOptions(ID(GetPropertyValue('HelperPrice1' + (selVal == '13' ? 'Lease' : '') + 'ClientId'))), false);
        cbxPrice2.addOption(GetOptions(ID(GetPropertyValue('HelperPrice2' + (selVal == '13' ? 'Lease' : '') + 'ClientId'))), false);

        if (cbxPrice1.hasClass('whitetext')) cbxPrice1.removeClass('whitetext');
        if (!cbxPrice1.hasClass('graytext')) cbxPrice1.addClass('graytext');

        if (cbxPrice2.hasClass('whitetext')) cbxPrice2.removeClass('whitetext');
        if (!cbxPrice2.hasClass('graytext')) cbxPrice2.addClass('graytext');
    }

    hashPrevValues['STypes'] = selVal;
}

function HighlightSddl(ddlName, defaultValue, defaultValue2) {
    var c = $("#" + GetPropertyValue(ddlName + 'ClientId'));
    if (c.hasClass('graytext')) c.removeClass('graytext');
    if (!c.hasClass('whitetext')) c.addClass('whitetext');
}

function FadeSddl(ddlName, defaultValue, defaultValue2) {
    var elem = ID(GetPropertyValue(ddlName + 'ClientId'));

    defaultValue = defaultValue.toUpperCase();
    if (defaultValue2 == undefined) defaultValue2 = '';
    else defaultValue2 = defaultValue2.toUpperCase();

    var val = GetControlValue(elem).toUpperCase();
    var bEqual = (val == defaultValue || val == defaultValue2 ? true : false);
    if (!bEqual) {
        if (isDecimal(val) && isDecimal(defaultValue2)) bEqual = parseFloat(val) == parseFloat(defaultValue2) ? true : false;
    }

    if (bEqual) {
        var c = $("#" + GetPropertyValue(ddlName + 'ClientId'));
        if (c.hasClass('whitetext')) c.removeClass('whitetext');
        if (!c.hasClass('graytext')) c.addClass('graytext');
    }
}

function OnFocusSddl(ddlName, defaultValue, defaultValue2) {
    //if (!($.browser.msie)) return;

    hashActiveSddl.put(ddlName, "focus");
}

function OnBlurSddl(ddlName, defaultValue, defaultValue2) {
    //if (!($.browser.msie)) return;

    if (!hashActiveSddl.containsKey(ddlName)) return;

    if (hashActiveSddl[ddlName] == "mouseout")
        FadeSddl(ddlName, defaultValue, defaultValue2);

    hashActiveSddl.remove(ddlName);
}

function OnMouseOverSddl(ddlName, defaultValue, defaultValue2) {
    HighlightSddl(ddlName, defaultValue, defaultValue2);

    //if ($.browser.msie) {
        if (hashActiveSddl.containsKey(ddlName)) {
            if (hashActiveSddl[ddlName] == "mouseout")
                hashActiveSddl[ddlName] = "focus";
        }
    //}
}

function OnMouseOutSddl(ddlName, defaultValue, defaultValue2) {
//    if (!($.browser.msie)) {
//        FadeSddl(ddlName, defaultValue, defaultValue2);
//        return;
//    }

    // There is no ddl in active list, i.e. ddl was not selected by user.
    if (!hashActiveSddl.containsKey(ddlName)) {
        FadeSddl(ddlName, defaultValue, defaultValue2);
        return;
    }

    hashActiveSddl[ddlName] = "mouseout";
}

function OnMouseOverStbx(tbxName, defaultValue, defaultValue2) {
    HighlightSddl(tbxName, defaultValue, defaultValue2);

    if (hashActiveSddl.containsKey(tbxName)) {
        if (hashActiveSddl[tbxName] == "mouseout")
            hashActiveSddl[tbxName] = "focus";
    }
}

function OnMouseOutStbx(tbxName, defaultValue, defaultValue2) {
    if (!hashActiveSddl.containsKey(tbxName)) {
        FadeSddl(tbxName, defaultValue, defaultValue2);
        return;
    }

    hashActiveSddl[tbxName] = "mouseout";
}

function OnFocusStbx(tbxName, defaultValue, defaultValue2) {
    if (defaultValue2 == undefined) defaultValue2 = '';

    var elem = ID(GetPropertyValue(tbxName + 'ClientId'));
    if (elem.value.toUpperCase() == defaultValue.toUpperCase() || elem.value.toUpperCase() == defaultValue2.toUpperCase()) elem.value = '';

    hashActiveSddl.put(tbxName, "focus");
}

function OnBlurStbx(tbxName, defaultValue, defaultValue2) {
    if (defaultValue2 == undefined) defaultValue2 = '';

    var elem = ID(GetPropertyValue(tbxName + 'ClientId'));
    if (elem.value.toUpperCase() == '' || elem.value.toUpperCase() == defaultValue.toUpperCase() || elem.value.toUpperCase() == defaultValue2.toUpperCase()) elem.value = defaultValue;

    if (!hashActiveSddl.containsKey(tbxName)) return;

    if (hashActiveSddl[tbxName] == "mouseout")
        FadeSddl(tbxName, defaultValue, defaultValue2);

    hashActiveSddl.remove(tbxName);
}

function isDecimal(val) {
    if ((/^-?\d+(\.\d+)?$/.test(val))) return true;
    if ((/^-?\d+(\,\d+)?$/.test(val))) return true;
    return false;
}

function GetObjCoded(suffix, clientIds) {
    var ary = GetPropertyValue(clientIds).split(',');
    for (var i = 0; i < ary.length; i++) {
        if (ary[i] != '') {
            var ary2 = ary[i].split('=');
            if (ary2.length == 2) {
                if (ary2[0] == suffix) return ID(ary2[1]);
            }
        }
    }

    return null;
}

function GetSearchTypeCheckImage(suffix) {
    return GetObjCoded(suffix, 'TypeImgClientIds');
}

function GetSearchTypeValue(suffix) {
    return GetObjCoded(suffix, 'TypeValueClientIds');
}

function GetSearchTypeId(suffix) {
    return GetObjCoded(suffix, 'TypeStyleIdClientIds');
}

function OnClickType(suffix) {
    var img = GetSearchTypeCheckImage(suffix);
    if (!img) return;

    var val = parseInt(GetSearchTypeValue(suffix).value);
    val = 1 - val;
    SetCheck(suffix, val);

    // Check other values.
    if (val == 1) {
        if (suffix == 'All') {
            ResetSearch_Types(0);
            ResetSearch_Styles(0);
        }
        else {
            SetCheck('All', 0);
            if (parseInt(suffix) < 100) ResetSearch_Types(parseInt(suffix));
            if (parseInt(suffix) >= 100) ResetSearch_Styles(parseInt(suffix));
        }
    }

    if (val == 0) {
        if(GetDetSearchType() == 0 && GetDetSearchStyle() == 0) SetCheck('All', 1);
    }

    // Change price dropdowns if Lease type selected or cleared.
    if (GetSearchTypeId(suffix).value == '13') {
        ChangePriceDll(val == 1 ? true : false, 'DetSearchPrices');
        hashPrevValues['DetLease'] = val == 1 ? 'Yes' : 'No';
    }
    else if (suffix == 'All' && hashPrevValues['DetLease'] == 'Yes') {
        ChangePriceDll(false, 'DetSearchPrices');
        hashPrevValues['DetLease'] = 'No';
    }
    else if (parseInt(suffix) < 100 && hashPrevValues['DetLease'] == 'Yes') {
        ChangePriceDll(false, 'DetSearchPrices');
        hashPrevValues['DetLease'] = 'No';
    }
}

function ChangePriceDll(isLease, idPart) {
    var cbxPrice1 = $("#" + GetPropertyValue(idPart + '1ClientId'));
    var cbxPrice2 = $("#" + GetPropertyValue(idPart + '2ClientId'));
    if (!cbxPrice1 || !cbxPrice2) return;

    cbxPrice1.removeOption(/./);
    cbxPrice2.removeOption(/./);

    cbxPrice1.addOption(GetOptions(ID(GetPropertyValue('HelperPrice1' + (isLease ? 'Lease' : '') + 'ClientId'))), false);
    cbxPrice2.addOption(GetOptions(ID(GetPropertyValue('HelperPrice2' + (isLease ? 'Lease' : '') + 'ClientId'))), false);

    if (cbxPrice1.hasClass('whitetext')) cbxPrice1.removeClass('whitetext');
    if (!cbxPrice1.hasClass('graytext')) cbxPrice1.addClass('graytext');

    if (cbxPrice2.hasClass('whitetext')) cbxPrice2.removeClass('whitetext');
    if (!cbxPrice2.hasClass('graytext')) cbxPrice2.addClass('graytext');
}

function ClearDdlSelectedOptions(objDdl) {
    for (var i = 0; i < objDdl.options.length; i++)
        objDdl.options[i].selected = false;
}

function OnChangePrice(ddlName, defaultValue, defaultValue2) {
    var elem = ID(GetPropertyValue(ddlName + 'ClientId'));
    if (!elem) return;
    var selVal = parseFloat(GetControlValue(elem));

    var priceIndex = ddlName.substring(ddlName.length - 1, ddlName.length);

    var elem2 = ID(GetPropertyValue(ddlName.substring(0, ddlName.length - 1) + (priceIndex == '1' ? '2' : '1') + 'ClientId'));
    if (!elem2) return;
    var selVal2 = parseFloat(GetControlValue(elem2));

    var bFound = false;

    if (priceIndex == '1') {
        // Select value in low price dropdown.
        if (selVal != 0) {
            if (selVal2 == 0 || selVal2 <= selVal) {
                // No value selected in high price dropdown or it's low than selected lower.
                for (var i = 0; i < elem2.options.length; i++) {
                    if (parseFloat(elem2.options[i].value) > selVal) {
                        if (elem2.options[i].selected) return;

                        bFound = true;

                        selVal2 = parseFloat(elem2.options[i].value);
                        elem2.options[i].selected = true;
                        break;
                    }
                }
            }
            else {
                bFound = true;
            }
        }
        else {
            bFound = true;
        }
    }
    else {
        // Select value in high price dropdown.
        if (selVal <= selVal2 && selVal != 0) {
            // Selected value in low price dropdown is higher.
            for (var i = elem2.options.length - 1; i >= 0; i--) {
                if (parseFloat(elem2.options[i].value) < selVal) {
                    if (elem2.options[i].selected) return;

                    bFound = true;

                    selVal2 = parseFloat(elem2.options[i].value);
                    elem2.options[i].selected = true;
                    break;
                }
            }
        }
        else {
            bFound = true;
        }
    }

    if (!bFound) {
        elem2.options[0].selected = true;
        selVal2 = 0;
    }

    if (selVal2 != 0) {
        if ($("#" + elem2.id).hasClass('graytext')) $("#" + elem2.id).removeClass('graytext');
        if (!$("#" + elem2.id).hasClass('whitetext')) $("#" + elem2.id).addClass('whitetext');
    }
    else {
        if ($("#" + elem2.id).hasClass('whitetext')) $("#" + elem2.id).removeClass('whitetext');
        if (!$("#" + elem2.id).hasClass('graytext')) $("#" + elem2.id).addClass('graytext');
    }
}

function ResetSearch_Types(skipId) {
    for (var i = 1; true; i++) {
        if (i == skipId) continue;

        if (!GetSearchTypeValue(i)) return 0;
        if (parseInt(GetSearchTypeValue(i).value) == 1) SetCheck(i, 0);
    }
}

function ResetSearch_Styles(skipId) {
    for (var i = 100; true; i++) {
        if (i == skipId) continue;

        if (!GetSearchTypeValue(i)) return 0;
        if (parseInt(GetSearchTypeValue(i).value) == 1) SetCheck(i, 0);
    }
}

function SetCheck(suffix, val) {
    var img = GetSearchTypeCheckImage(suffix);
    if (!img) return;

    img.src = 'images/06-check' + (val == 0 ? '' : '-on') + '.png';
    GetSearchTypeValue(suffix).value = val;
}

function GetDetSearchType() {
    for (var i = 1; true; i++) {
        if (!GetSearchTypeValue(i)) return 0;
        if (parseInt(GetSearchTypeValue(i).value) == 1)
            return parseInt(GetSearchTypeId(i).value);
    }

    return 0;
}

function GetDetSearchStyle() {
    for (var i = 100; true; i++) {
        if (!GetSearchTypeValue(i)) return 0;
        if (parseInt(GetSearchTypeValue(i).value) == 1)
            return parseInt(GetSearchTypeId(i).value);
    }

    return 0;
}

function GetValueInArray(ary, listingId) {
    var retVal = '';
    for (var i = 0; i < ary.length; i++) {
        var ary2 = ary[i].split('=');
        if (ary2.length == 2) {
            if (ary2[0] == listingId) {
                retVal = ary2[1];
                break;
            }
        }
    }

    return retVal;
}

function OnClickMapPrevNext(listingId, arrow) {
    var index = GetArrayIndexOfProperty(listingId);
    if (index == -1) return;

    var numElements = GetMaxIndex();
    if (aryProperties.length < numElements) numElements = aryProperties.length;

    var bFound = true;
    var newIndex = index + arrow;
    if (newIndex < 0 || newIndex > numElements - 1) return;
    while (!aryProperties[newIndex].hasMapCoords()) {
        newIndex += arrow;
        if (newIndex < 0 || newIndex > numElements - 1) {
            bFound = false;
            break;
        }
    }

    if (!bFound) return;

    OpenInfoWindow(aryProperties[newIndex]);
}

function OnClickLnk(listingId, btnId) {
    if (btnId == undefined) btnId = '';
    if (listingId == undefined) listingId = 0;
    if (btnId == 'ibtPrint') {
        if (isFinite(hashPrevValues['LastSelectedListingId']))
            listingId = parseInt(hashPrevValues['LastSelectedListingId']);
    }

    var curTypeId = GetPropertyValue('TypeId')

    var newType = '';
    var newFilter = '';
    var newMLSNumbers = '';

    if (curTypeId == 0) newType = "Featured Properties";
    if (curTypeId == 1) newType = "Open Houses";
    if (curTypeId == 2) newType = "New Listings";
    if (curTypeId == 3) newType = "Quick Search";
    if (curTypeId == 4) newType = "Favorites";
    if (curTypeId == 5) newType = "Detail Search";
    if (curTypeId == 6) newType = "DG&Co Listings";
    if (curTypeId == 7) newType = "Modern Houses";

//    if (newType == 'Detail Search') newMLSNumbers = GetMLSNumbers();
//    if (newType == 'Detail Search' || newType == 'Quick Search') newFilter = GetFilterExpression(newType == 'Detail Search' ? false : true);
    newMLSNumbers = GetMLSNumbers();
    newFilter = GetFilterExpression(newType == 'Detail Search' ? false : true);

    var newNumberOfProperties = 0;
    if (GetPropertyValue('NumberOfProperties') != "") newNumberOfProperties = GetMaxIndex();

    DG2WebService.SaveCurrentState(newType, newFilter, newMLSNumbers, pageMode, newNumberOfProperties);
    DG2WebService.SaveCurrentListingId(listingId);

    SetPropertyValue('LastSelectedListingId', listingId);
    hashPrevValues['LastSelectedListingId'] = listingId;

    return true;
}

function IsFavoritesMode() {
    return parseInt(GetPropertyValue('TypeId')) == 4 ? true : false;
}

function OnClickClearSearch() {
    ClearQuickSearch();

    return false;
}

function OnChangeSddl(ddlName, defaultValue, defaultValue2) {
    if (defaultValue2 == undefined) defaultValue2 = '';

    var btnSearch = $("#" + GetPropertyValue('ClearSearchClientId'));

    val = GetControlValue(ID(GetPropertyValue(ddlName + 'ClientId')));
    if (isDecimal(val) && val != 0) {
        btnSearch.show();
        return;
    } else if (val.toUpperCase() != defaultValue.toUpperCase() && val.toUpperCase() != defaultValue2.toUpperCase() && val.toUpperCase() != '') {
        btnSearch.show();
        return;
    }

    // Maybe the filter has been cleared by user.

    // Address
    if (ddlName != 'SAddress') {
        val = GetControlValue(ID(GetPropertyValue('SAddressClientId')));
        if (val.toUpperCase() != 'SPECIFIC ADDRESS' && val.toUpperCase() != 'ADDRESS' && val.toUpperCase() != '') {
            btnSearch.show();
            return;
        }
    }

    // City.
    if (ddlName != 'SCities') {
        val = GetControlValue(ID(GetPropertyValue('SCitiesClientId')));
        if (val.toUpperCase() != 'DALLAS' && val.toUpperCase() != 'ALL CITIES') {
            btnSearch.show();
            return;
        }
    }

    // Price 1.
    if (ddlName != 'SPrice1') {
        val = GetControlValue(ID(GetPropertyValue('SPrices1ClientId')));
        val = parseFloat(val);
        if (val != 0) {
            btnSearch.show();
            return;
        }
    }

    // Price 2.
    if (ddlName != 'SPrice2') {
        val = GetControlValue(ID(GetPropertyValue('SPrices2ClientId')));
        val = parseFloat(val);
        if (val != 0) {
            btnSearch.show();
            return;
        }
    }

    // Area.
    if (ddlName != 'SAreas') {
        val = GetControlValue(ID(GetPropertyValue('SAreasClientId')));
        if (val.toUpperCase() != 'CHOOSE AREA') {
            btnSearch.show();
            return;
        }
    }

    // Type.
    if (ddlName != 'STypes') {
        val = GetControlValue(ID(GetPropertyValue('STypesClientId')));
        if (val.toUpperCase() != 'CHOOSE TYPE' && val.toUpperCase() != '') {
            btnSearch.show();
            return;
        }
    }

    // Style.
    if (ddlName != 'SStyles') {
        val = GetControlValue(ID(GetPropertyValue('SStylesClientId')));
        if (('' + val).toUpperCase() != '0') {
            btnSearch.show();
            return;
        }
    }

    ///////btnSearch.hide();
}

function ClearDetSearch() {
    // MLS Numbers
    ID(GetPropertyValue('DetSearchMLSClientId')).value = "";

    // City
    ID(GetPropertyValue('DetSearchCityClientId')).value = "";

    // Zip code
    ID(GetPropertyValue('DetSearchZipCodeClientId')).value = "";

    // Area.
    val = GetControlValue(ID(GetPropertyValue('DetSearchAreasClientId')));
    if (val.toUpperCase() != 'CHOOSE AREA') {
        $("#" + GetPropertyValue('DetSearchAreasClientId')).selectOptions('Choose Area');
        FadeSddl('DetSearchAreas', 'Choose Area');
    }

    // Address
    ID(GetPropertyValue('DetSearchAddressClientId')).value = "";

    // Agent
    ID(GetPropertyValue('DetSearchAgentClientId')).value = "";

    // Elementry school
    val = GetControlValue(ID(GetPropertyValue('DetSearchElementrySchoolClientId')));
    if (val.toUpperCase() != 'Choose elementry school' && val.toUpperCase() != 'Elementry school' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchElementrySchoolClientId')).selectOptions('Choose elementry school');
        FadeSddl('DetSearchElementrySchool', 'Choose elementry school');
    }

    // Middle school
    val = GetControlValue(ID(GetPropertyValue('DetSearchMiddleSchoolClientId')));
    if (val.toUpperCase() != 'Choose middle school' && val.toUpperCase() != 'Middle school' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchMiddleSchoolClientId')).selectOptions('Choose middle school');
        FadeSddl('DetSearchMiddleSchool', 'Choose middle school');
    }

    // High school
    val = GetControlValue(ID(GetPropertyValue('DetSearchHighSchoolClientId')));
    if (val.toUpperCase() != 'Choose high school' && val.toUpperCase() != 'High school' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchHighSchoolClientId')).selectOptions('Choose high school');
        FadeSddl('DetSearchHighSchool', 'Choose high school');
    }

    // Price 1.
    val = GetControlValue(ID(GetPropertyValue('DetSearchPrices1ClientId')));
    val = parseFloat(val);
    if (val != 0) {
        ID(GetPropertyValue('DetSearchPrices1ClientId')).options[0].selected = true;
        FadeSddl('DetSearchPrices1', 'Your low price', '0');
    }

    // Price 2.
    val = GetControlValue(ID(GetPropertyValue('DetSearchPrices2ClientId')));
    val = parseFloat(val);
    if (val != 0) {
        ID(GetPropertyValue('DetSearchPrices2ClientId')).options[0].selected = true;
        FadeSddl('DetSearchPrices2', 'Your high price', '0');
    }

    // Beds
    val = GetControlValue(ID(GetPropertyValue('DetSearchBedroomsClientId')));
    if (val.toUpperCase() != 'Choose bedrooms number' && val.toUpperCase() != 'Bedrooms number' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchBedroomsClientId')).selectOptions('Choose bedrooms number');
        FadeSddl('DetSearchBedrooms', 'Choose bedrooms number');
    }

    // Baths
    val = GetControlValue(ID(GetPropertyValue('DetSearchBathroomsClientId')));
    if (val.toUpperCase() != 'Choose bathrooms number' && val.toUpperCase() != 'Bathrooms number' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchBathroomsClientId')).selectOptions('Choose bathrooms number');
        FadeSddl('DetSearchBathrooms', 'Choose bathrooms number');
    }

    // Garages
    val = GetControlValue(ID(GetPropertyValue('DetSearchGaragesClientId')));
    if (val.toUpperCase() != 'Choose garages number' && val.toUpperCase() != 'Garages number' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchGaragesClientId')).selectOptions('Choose garages number');
        FadeSddl('DetSearchGarages', 'Choose garages number');
    }

    // Stories
    val = GetControlValue(ID(GetPropertyValue('DetSearchStoriesClientId')));
    if (val.toUpperCase() != 'Choose stories number' && val.toUpperCase() != 'Stories number' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchStoriesClientId')).selectOptions('Choose stories number');
        FadeSddl('DetSearchStories', 'Choose stories number');
    }

    // Acres
    val = GetControlValue(ID(GetPropertyValue('DetSearchAcresClientId')));
    if (val.toUpperCase() != 'Choose acres' && val.toUpperCase() != 'Acres' && val.toUpperCase() != '') {
        $("#" + GetPropertyValue('DetSearchAcresClientId')).selectOptions('Choose acres');
        FadeSddl('DetSearchAcres', 'Choose acres');
    }

    ResetSearch_Styles();
    ResetSearch_Types();
    SetCheck('All', 1);
    ChangePriceDll(false, 'DetSearchPrices');
    hashPrevValues['DetLease'] = 'No';
}

function OnClickClearDetSearch() {
    ClearDetSearch();

    return false;
}

function SetCookie(name, value, days) {
    if (days == undefined) days = 365;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function GetCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function EraseCookie(name) {
    createCookie(name, "", -1);
}
