﻿/// <reference path="../jquery-1.2.6-intellisense.js" />

var _agent;

var _currentScreen = 1;  
var _currencyId;
var _unitId;
var _isFeaturedProperty;


// OnLoad Function
jQuery(document).ready(function() {
    showFeaturedProperties();
    initializeCorousel('#featuredImageCorousel');
    initializeAgentObject();
    displayAgentOnMap();

    $('#featuredImageCorousel').find('img').click(function() {
        _isFeaturedProperty = true;
        _currentScreen = 3;
        initializeFeaturedPropertyLinks(this);
    });

    $('#breadcrumb_Home').click(function() {
        if (_currentScreen == 1)
            return;
        var breadCrumb = $(this).parents('.breadcrumb');
        breadCrumb.find('.breadcrumb_link').addClass('hidden');
        showFeaturedProperties();
        initializeCorousel('#featuredImageCorousel');
    });

    $('#breadcrumb_PropertySearch').click(function() {
      
        if (_currentScreen == 2)
            return;
        _currentScreen = 2;

        $('#breadcrumb_PropertySearch').addClass('hidden');
        showSearchResult();

        showResultOnMap();
    });


    $('#emaillisting').click(function() {

      
        var propertyid = $("#print_propertyid").val();
        var countryid = $("#print_countryid").val();
        var currencyid = _currencyId;
        var unitid = _unitId;
        var culture = getCurrentCulture();
        var queryString = "PropertyId=" + propertyid + "&CountryId=" + countryid + "&Currencyid=" + currencyid + "&UnitId=" + unitid + "&Culture=" + culture;
        var resultstring = " http://www.proxiopro.com/mls/miami/PropertyView.aspx?" + queryString;
        var string1 = page_refnumber + ": " + $('#print_refno').val() + "\n" + $('#print_style').val() + "\n" + $('#print_address').val() + "\n" + page_viewlistingdetails + ": ";
        var mailText = string1 + "<a href=\"" + resultstring + "\">" + page_clickhere + "</a>";
        displayAgentContactForm(mailText);

    });



    $('#printpage').click(function() {

        var propertyid = $("#print_propertyid").val();
        var countryid = $("#print_countryid").val();
        var currencyid = _currencyId;
        var unitid = _unitId;
        var culture = getCurrentCulture();
        var queryString = "PropertyId=" + propertyid + "&CountryId=" + countryid + "&Currencyid=" + currencyid + "&UnitId=" + unitid + "&Culture=" + culture + "&Print=" + "Yes";
        var w = 800
        var h = 600
        if (window.screen) {
            w = window.screen.availWidth;
            h = window.screen.availHeight;
        }
        //  window.open("PropertyView.aspx?" + queryString, 'newwin', 'width=' + w-10 + ',height=' + h-10 + ',top=0,left=0'); 
        window.open("PropertyView.aspx?" + queryString);



    });





    $('#searchButton').click(function() {
        $("#hdntabinfo").val($("#hdntabinfoCurrent").val());
        _currentScreen = 2;
        _isFeaturedProperty = false;
        $('#breadcrumb_Home').removeClass('hidden');
        $('#breadcrumb_PropertySearch').addClass('hidden');
        //        $('#breadcrumb_PropertyDetail').addClass('hidden');
        showSearchLoadingBar();
        $(".ddPageSize").val('10');

        var tabselected = $("#hdntabinfo").val();
        if (tabselected == null)
            return;
        if (tabselected == "#fragment-2") {
          
            var agencyAgentSearchParam = getAgentSearchParam();
            if (agencyAgentSearchParam == undefined)
                return;
            showSearchResult();
            initializeagentPagination(agencyAgentSearchParam);

        }
        else if (tabselected == "#fragment-1") {

            var propertySearchParam = getPropertySearchParam();
            if (propertySearchParam == undefined)
                return;
            showSearchResult();
            initializePagination(propertySearchParam);
        }
        else if (tabselected == "#fragment-3") {

            var AgencySearchParam = getAgencySearchParam();
            if (AgencySearchParam == undefined)
                return;
            showSearchResult();
            initializeagencyPagination(AgencySearchParam);

        }

    });


    $('.imgMagnifyingGlass').click(function() {
        var resultParent = jQuery(this).parents('.divSearchResult');
        var propertyId = resultParent.find("[accessKey='hdnPropertyId']").val();
        var countryId = resultParent.find("[accessKey='hdnCountryId']").val();

        getPropertyDetailInformation(propertyId, countryId);
    });

    $('.contactMe').click(function() {
      // displayContactForm();
    });
});

function hideAllScrenes() {
    $('#divFeaturedPropertyMain').addClass("hidden");
    $('#divSearchResultsMain').addClass("hidden");
    $('#divPropetyDetailContainer').addClass("hidden");
}

function initializeFeaturedPropertyLinks(sender) {
    var text = $(sender).attr("name");

    var arr = text.split(',');

    _currencyId = jQuery("[name$='ddCurrency']").find('option:selected').val();
    _unitId = 1632;

    getPropertyDetailInformation(arr[0], arr[1]);
}

function initializeAgentObject() {
    var tempObj = new Object();
    var temp = $('#hdnAgentInformation').val();
    tempObj = temp;
    $(temp);
};

function displayAgentOnMap() {
    var latitude = $('#hdnLatitude').val();
    var longitude = $('#hdnLongitude').val();

    latitude = latitude.replace(",", ".");
    longitude = longitude.replace(",", ".");

    $('#gMap').jmap('init', { 'mapType': 'map', 'mapCenter': [latitude, longitude], 'mapEnableType': true }, function(map, element, options) {
        var E_STYLE_temp = new EStyle("Images/stem7.png", new GSize(24, 24), "estyle2", new GPoint(-10, 23));
        ew = new EWindow(map, E_STYLE_temp);
        map.addOverlay(ew);
        // ========== Close the EWindow if theres a map click ==========
        GEvent.addListener(map, "click", function(overlay, point) {
            if (!overlay) {
                ew.hide();
            }
        });
    });
    addMarker(latitude, longitude, $("#lblAgentAddress").html());

};

//--------  Corousel Related Functions  -------------

// Initialize the Corousel
function initializeCorousel(selector) {
    var corousel = jQuery(selector);
    var imageCount = corousel.find('img').length;
    if (imageCount == 0)
        return;
    corousel.jcarousel({
        visible: 3,
        scroll: 3
    });

    corousel.find('img').mouseover(function() {
        corouselImageClicked(this);
    });
}

// When Corousel Image is clicked
function corouselImageClicked(source) {
    var slideShow = jQuery(source).parents('.divSlideShow');
    slideShow.find('.mainImage').attr("src", source.longDesc);
};


// Get featured Property Images Through Ajax
function showFeaturedProperties() {
    hideAllScrenes();
    $('#divFeaturedPropertyMain').removeClass("hidden");
    displayAgentOnMap();
}

//// Display Featured properties Featched through Ajax
//function displayFeaturedProperties(content) {
//    var rightAreaContent = $('#rightAreaContent');
//    rightAreaContent.html("");
//    var tplFeaturedPropertyMain = $('#tplFeaturedPropertyMain');
//    var t = $.template(tplFeaturedPropertyMain.html());

//    rightAreaContent.append(t, {
//        TxtFeaturedProperty: content.d.TxtFeaturedProperty,
//        PrimaryImage: content.d.CorouselImages[0].PosterImageUrl
//    });

//    var corouselList = rightAreaContent.find("#mycarousel");

//    var tplCorouselImageTxt = $('#tplCorouselImage').html();
//    var corouselImages = content.d.CorouselImages;

//    for (var i = 0; i < corouselImages.length; i++) {
//        var t1 = $.template(tplCorouselImageTxt);
//        corouselList.append(t1, corouselImages[i]);
//    }

//    // Initialize the corousel as we have changed the HTML
//    initializeCorousel('#mycarousel');
//}


//---------------   Property Search Related Functions   ---------------------

function pageUpdateStarted() {
    showSearchLoadingBar();
    removeMarkers();
}

function showSearchLoadingBar() {
    $('.noItemsFound').addClass('hidden');
    var resultContainer = $('#divSearchResultsMain');
    resultContainer.find("#divSearchResultContainer").addClass("notVisible");
    resultContainer.find("#searchResultsContainer").addClass("notVisible");
    resultContainer.addClass("progressBar");
}

function showSearchResults() {
    var resultContainer = $('#divSearchResultsMain');

    resultContainer.find("#divSearchResultContainer").removeClass("notVisible");
    resultContainer.find("#searchResultsContainer").removeClass("notVisible");
    resultContainer.removeClass("progressBar");
}

function noSearchResultFound() {
    $('.noItemsFound').removeClass('hidden');
    var resultContainer = $('#divSearchResultsMain');
    resultContainer.find("#divSearchResultContainer").removeClass("notVisible");
    resultContainer.removeClass("progressBar");
    setContextSpecificText();
}

function searchPageChanged() {
    $('.imgMagnifyingGlass').mouseover(function() {
        highlightThisProperty(this);
    }).click(function() {
       
        navigateToPropertryDetail(this);
    });

    $('.imgSearchResult').mouseover(function() {
        highlightThisProperty(this);
    }).click(function() {
        navigateToPropertryDetail(this);
    });
    
    initializeListingMail();

    showSearchResults();
};

function navigateToPropertryDetail(sender) {
    var resultParent = jQuery(sender).parents('.divSearchResult');
    var propertyId = resultParent.find("[accessKey='hdnPropertyId']").val();
    var countryId = resultParent.find("[accessKey='hdnCountryId']").val();
    getPropertyDetailInformation(propertyId, countryId);

    $('#breadcrumb_PropertySearch').removeClass('hidden');
    //        $('#breadcrumb_PropertyDetail').removeClass('hidden');
    _currentScreen = 3;
};

function highlightThisProperty(sender) {

    var resutl = $(sender).parents('.divSearchResult');
    var latitude = resutl.find("[accessKey='hdnLatitude']").val();
    var longitude = resutl.find("[accessKey='hdnLongitude']").val();
    centerMap(latitude, longitude);
};

function noResultsFound() {

};

var propertyPager;
var agentPage;
var officePager;

function initializePagination(propertySearchParam) {
    if (propertyPager == null || propertyPager == undefined)
        propertyPager = new Pager();
    propertyPager.initialize(propertySearchParam);
};
function initializeagentPagination(agencyAgentSearchParam) {
    if (agentPage == null || agentPage == undefined)
        agentPage = new AgentPager();
    agentPage.initialize(agencyAgentSearchParam);

};

function initializeagencyPagination(AgencySearchParam) {
    if (officePager == null || officePager == undefined)
        officePager = new AgencyPager();
    officePager.initialize(AgencySearchParam);

};

function showSearchResult() {

    hideAllScrenes();

    $('#divSearchResultsMain').removeClass("hidden");
    
};

function displaySearchResult() {
}

function initializeListingMail() {
    $('.imgSendMail').click(function() {
     
        var resultParent = jQuery(this).parents('.divSearchResult');
        var propertyId = resultParent.find("[accessKey='hdnPropertyId']").val();
        var countryId = resultParent.find("[accessKey='hdnCountryId']").val();
        var ListingAgentId = resultParent.find("[accessKey='hdnpropertyListingAgentId']").val();
        document.getElementById("hdnCurrentPropertyAgentlistingId").value = ListingAgentId;
        var refNumber = resultParent.find(".search_listingId").text();
        var address = resultParent.find(".result_Address1").text() + ", " + resultParent.find(".result_Address2").text();

        var mailText = page_contactProperty.replace("txt_RefNumber", refNumber);
        mailText = mailText.replace("txt_Address", address);

        displayContactForm(mailText);
    });
}

function updateSearchResults(searchResults) {


    var tabselected = $("#hdntabinfo").val();
    if (tabselected == "#fragment-2") {

        var tplSearchResultTxt = $('#tplAgentSearch').html();
        var SearchResultContainer = $('#searchResultsContainer');
        SearchResultContainer.html("");

        for (var i = 0; i < searchResults.length; i++) {
            var result = searchResults[i];
            if (result.AgentImageUrl == "") {
                result.AgentImageUrl = "Images/Agent_noimage.png";
            }

            // var address = result.AgencyName + "<br />" + result.AddressLine2;
            var address = result.CityName;
            addMarker(result.Latitude, result.Longitude, address);

            var t = $.template(tplSearchResultTxt);
            //        if (result.VirtualTourUrl == "") {
            //            result.VirtualTourClass = "inVisible";
            //        }        

            SearchResultContainer.append(t, result);
        }


        SearchResultContainer.find('#agentemailicon').click(function() {


            var resultParent = jQuery(this).parents('.divSearchResult');
            var agentemail = resultParent.find("[accessKey='hdnagentEmail']").val();
            document.getElementById('hdnAgentEmailID').value = agentemail;
            var agentcountryid = resultParent.find("[accessKey='hdnagentCountryId']").val();
            var mailbody = "";
            displayAgencyContactForm(mailbody);

        });

    }
    else if (tabselected == "#fragment-1") {

        var tplSearchResultTxt = $('#tplPropertySearchResult').html();
        var SearchResultContainer = $('#searchResultsContainer');
        SearchResultContainer.html("");

        for (var i = 0; i < searchResults.length; i++) {
            var result = searchResults[i];
            if (result.PrimaryImageUrl == "") {
                result.PrimaryImageUrl = "Images/propSearchResult/prop-result-image.jpg";
            }

            var address = result.AddressLine1 + "<br />" + result.AddressLine2;
            addMarker(result.Latitude, result.Longitude, address);

            var t = $.template(tplSearchResultTxt);
            var propertyclassid= result.PropertyClassID;
            if (propertyclassid == 169 || propertyclassid == 170 || propertyclassid == 171 || propertyclassid == 173)
                result.bedBath = "inVisible";       
            
            
            
            
            if (result.VirtualTourUrl == "") {
                result.VirtualTourClass = "inVisible";
            }

            SearchResultContainer.append(t, result);
        }
    }
    else if (tabselected == "#fragment-3") {

       var tplSearchResultTxt = $('#tplAgencySearch').html();
        var SearchResultContainer = $('#searchResultsContainer');
        SearchResultContainer.html("");

        for (var i = 0; i < searchResults.length; i++) {
            var result = searchResults[i];
            if (result.OfficeImage == "") {
                result.OfficeImage = "Images/Logo_noimage.png";
            }

            var address = result.StreetName + "," + result.CityName;
            addMarker(result.Latitude, result.Longitude, address);

            var t = $.template(tplSearchResultTxt);
           

            SearchResultContainer.append(t, result);
        }
    }
    
    setContextSpecificText();
};


function getAgencySearchParam() {

    var listingAgencyId = $("#hdnAgencyId").val();
    var agencysearchName = jQuery("[name$='txtAgencySearchName']").val();

    var ddagencyCountry = $("[name$='ddagencycountry']");
    var agencycountryId = ddagencyCountry.val();

    var ddAgencyCityid = jQuery("[name$='ddagencyCity']");
    var acgencyCity = ddAgencyCityid.val()
    var ddagencyRegionId = jQuery("[name$='ddagencyState']");
    var agencyRegionId = ddagencyRegionId.val();

    var agencyLanguageId = jQuery("[name$='agencyLanguage']").find("option:selected").val();
    var agencyTextSpecialities = jQuery("[name$='txtagencyspecialities']").val();


    var AgencySearchParam = "{AgencyId: ";
    AgencySearchParam += listingAgencyId;
    AgencySearchParam += ", CountryId: ";
    AgencySearchParam += agencycountryId;
    AgencySearchParam += ", CityName: '";
    AgencySearchParam += acgencyCity;
    AgencySearchParam += "', RegionName: '";
    AgencySearchParam += agencyRegionId;
    AgencySearchParam += "', LanguageId: ";
    AgencySearchParam += agencyLanguageId;
    AgencySearchParam += ", Specialities:'";
    AgencySearchParam += agencyTextSpecialities;
    AgencySearchParam += "',AgencyName: '";
    AgencySearchParam += agencysearchName;

    AgencySearchParam += "'}";
    return AgencySearchParam;

};



function getAgentSearchParam()
{
    var ddagencyCountry = $("[name$='ddagentcountry']");
     var agencycountryId = ddagencyCountry.val();

  // var officeId = $("#hdnOfficeId").val();
    var ddAgenctCityid = jQuery("[name$='ddagentCity']");
    var acgentCity = ddAgenctCityid.val()    
    var ddagentRegionId=jQuery("[name$='ddagentState']");
    var agentRegionId= ddagentRegionId.val();
    var agentFirstName = jQuery("[name$='txtagentFirstName']");
    //if(agentFirstName !=null)
        agentFirstName = jQuery("[name$='txtagentFirstName']").val();

    var agentLastName = jQuery("[name$='txtagentlastName']");
    //if(agentLastName !=null)
    agentLastName = jQuery("[name$='txtagentlastName']").val();
 
    var agentLanguageId = jQuery("[name$='ddagentlanguage']").find("option:selected").val();

  
  //  var agentLanguageId= ddAgentLanguageId.val();
    var agentTextSpecialities = jQuery("[name$='txtspecialities']");
    //if(agentTextSpecialities !=null)
        agentTextSpecialities = jQuery("[name$='txtspecialities']").val();
    var listingAgencyId = $("#hdnAgencyId").val();

    var agencyAgentSearchParam = "{AgencyID: ";
    agencyAgentSearchParam += listingAgencyId;
    agencyAgentSearchParam += " ,CountryID: ";
    agencyAgentSearchParam += agencycountryId;
    agencyAgentSearchParam += " ,RegionName: '";
    agencyAgentSearchParam += agentRegionId;
    agencyAgentSearchParam += "',CityName: '";
    agencyAgentSearchParam += acgentCity;
    agencyAgentSearchParam += "',FirstName: '";
    agencyAgentSearchParam += agentFirstName;
    agencyAgentSearchParam += "',LastName: '";
    agencyAgentSearchParam += agentLastName;
    agencyAgentSearchParam += "',LanguageId: ";
    agencyAgentSearchParam += agentLanguageId;
    agencyAgentSearchParam += ",Specialities: '";
    agencyAgentSearchParam += agentTextSpecialities;
    agencyAgentSearchParam += "'}";

    return agencyAgentSearchParam;

};




function getPropertySearchParam() {
    var ddCountry = $("[name$='ddCountry']");
    var countryId = ddCountry.val();
    var countryName = $("select[id*='ddCountry'] :selected").text();
    if (countryId == -1 || countryId == undefined) {
        alert(page_pleaseSelectCountry);
        ddCountry.focus();
        return;
    }
   
    
    var ddRegion = jQuery("[name$='ddState']");
    var regionId = ddRegion.val();
    var regionName = $("select[id*='ddState'] :selected").text();
    if (regionId == "-1")
        regionName = "";
    
    var ddCity = jQuery("[name$='ddCity']");
    var cityId = ddCity.val();
    var cityName = $("select[id*='ddCity'] :selected").text();
    if (cityId == "-1")
        cityName = "";

    var txtzipCode = $("input[id*='txtZipCode']"); //jQuery("[name$='txtZipCode']");
    var zipCode = "";
    if (txtzipCode != null && txtzipCode != undefined)
        zipCode = txtzipCode.val();
    
    
    var propertyClassId = jQuery("[name$='ddPropertyClass']").val();
    var bedRoomCount = jQuery("[name$='ddBedRooms']").val();
    var bathRoomCount = jQuery("[name$='ddBathRooms']").val();
    var minPrice = jQuery("[name$='txtMinPrice']").val();
    var maxPrice = jQuery("[name$='txtMaxPrice']").val();
    var minArea = jQuery("[name$='txtLandAreaMin']").val();
    var maxArea = jQuery("[name$='txtLandAreaMax']").val();
    var txtFreeText = jQuery("[name$='txtFreeText']").val();
   
    _currencyId = jQuery("[name$='ddCurrency']").find('option:selected').val();
    _unitId = jQuery("[name$='ddAreaUnit']").find('option:selected').val();
    var listingType = 2;
    
    

    if ((minPrice == null) || (minPrice.length == 0)) {
        minPrice = 0;
    }
    if ((maxPrice == null) || (maxPrice.length == 0)) {
        maxPrice = 0;
    }

    var url = "NewPropertySearch.aspx?CountryID=" + countryId + "&CountryName=" + countryName + "&RegionID=" + regionId + "&RegionName=" + regionName + "&CityID=" + cityId + "&CityName=" + cityName;
    url += "&BedRooms=" + bedRoomCount + "&BathRooms=" + bathRoomCount + "&MinPrice=" + minPrice + "&MaxPrice=" + maxPrice + "&CurrencyID=" + _currencyId + "&ClassID=" + propertyClassId;
    url += "&DUnit=" + _unitId + "&PostCode=" + zipCode + "&FreeText=" + txtFreeText;

    window.location = url;
    return;
    
    divSearchLocation = $(".divSearchLocation");
//    divSearchLocation.html(page_in + " ");

//    if (cityId != -1) {
//        divSearchLocation.append(ddCity.find("option:selected").text() + ", ");
//        if (regionId != -1) {
//            divSearchLocation.append(ddRegion.find("option:selected").text() + ", ");
//        }
//    }
    //    divSearchLocation.append(ddCountry.find("option:selected").text());

    document.getElementById('hdnPriceSearchInfo').value;

    var priceoption = $("#hdnPriceSearchInfo").val();

    var listingAgentId = $("#hdnAgentId").val();
    var listingAgencyId = $("#hdnAgencyId").val();
    var officeId = $("#hdnOfficeId").val();
    var officeType = $("#hdnOfficeType").val();

    var propertySearchParam = "{ListingAgentId: ";
    propertySearchParam += listingAgentId;
    propertySearchParam += ", ListingAgencyId: ";
    propertySearchParam += listingAgencyId;
    propertySearchParam += ", ListingOfficeId: ";
    propertySearchParam += officeId;
    propertySearchParam += ", OfficeType: '";
    propertySearchParam += officeType;
    propertySearchParam += "', PriceOptionType: '";
    propertySearchParam += priceoption;
    propertySearchParam += "', CountryId: ";
    propertySearchParam += countryId;
    propertySearchParam += " ,RegionId: '";
    propertySearchParam += regionId;
    propertySearchParam += "',CityId: '";
    propertySearchParam += cityId;
    propertySearchParam += "', CurrencyId: ";
    propertySearchParam += _currencyId;
    propertySearchParam += ", MinimumPrice: ";
    propertySearchParam += minPrice;
    propertySearchParam += ", MaximumPrice: ";
    propertySearchParam += maxPrice;
    propertySearchParam += ", BedRooms: ";
    propertySearchParam += bedRoomCount;
    propertySearchParam += ", BathRooms: ";
    propertySearchParam += bathRoomCount;
    propertySearchParam += ", CountryId: ";
    propertySearchParam += countryId;
    propertySearchParam += ", UnitId: ";
    propertySearchParam += _unitId;
    propertySearchParam += ", MinLandArea: ";
    propertySearchParam += minArea;
    propertySearchParam += ", MaxLandArea: ";
    propertySearchParam += maxArea;

    propertySearchParam += ",ClassId: ";
    propertySearchParam += propertyClassId;
    
    propertySearchParam += ",ListingType: ";
    propertySearchParam += listingType;


    propertySearchParam += "}";

    return propertySearchParam;
};


// Google Map Related Functions


var markerArray = new Array();

function addMarker(latitude, longitude, pointHTML) {
    if( latitude <=0 && longitude <=0 )
    return false;
    if (pointHTML == undefined)
        pointHTML = "";

    jQuery('#gMap').jmap('AddMarker', {
        'pointLatLng': [latitude, longitude],
        'pointIsRemovable': false,
        'pointIsDraggable': false
    }, function(marker, options) {
        markerArray.push(marker);

        var infoWindowHtml = getInfoWindowHtml(pointHTML);
        GEvent.addListener(marker, "click", function() {
            ew.openOnMarker(marker, infoWindowHtml);
        });
    });
    return false;
}

function removeMarkers() {
    var markerArrayLength = markerArray.length;
    for (var i = markerArrayLength; i > 0; i--) {
        markerArray[i - 1].remove();
        markerArray.pop();
    }
    ew.hide();
}

function showResultOnMap() {
    var searchResults = $('.divSearchResult');
    var resultCount = searchResults.length;

    searchResults.each(function() {
        var resultParent = $(this);
        var latitude = resultParent.find("[accessKey='hdnLatitude']").val();
        var longitude = resultParent.find("[accessKey='hdnLongitude']").val();
        var address = resultParent.find(".result_Address").text();
          if( latitude ==0 && longitude == 0 )
            {
                addMarker(latitude, longitude, address);
            }
    });
}

function centerMap(latitude, longitude) {

    latitude = latitude.replace(",", ".");
    longitude = longitude.replace(",", ".");
    
    if( latitude ==0 && longitude == 0 )
    {
         jQuery('#divNoMapRequest').removeClass("inVisible");
         return;
    }
    else
    {
        jQuery('#divNoMapRequest').addClass("inVisible");
    }
    jQuery('#gMap').jmap('MoveTo', {
        'mapCenter': [latitude, longitude]
    });
}


// This function just makes a pretty table for the EWindow contents
function getInfoWindowHtml(content, header) {
    var infoWindowContent = '<table border="0" cellpadding="0" cellspacing="0" style="width:160px;">';
    
    if (header != undefined && header != '') {
        infoWindowContent += '<tr><td width="100%" class="EWTitle" nowrap>' + header + '<\/td><\/tr>';
    }

    infoWindowContent += '<tr><td><div class="infoWindowContent">' + content + '</div><\/td><\/tr><\/table>';

    return infoWindowContent;
}


// Property Detail Related Functions

function getPropertyDetailInformation(propertyId, countryId) {
    document.getElementById("print_propertyid").value = propertyId;
    document.getElementById("print_countryid").value = countryId;
   // $("#print_propertyid").val() = propertyId;
   // $("#print_countryid").val() = countryId;
    
    var postBackData = "{PropertyId : ";
    postBackData += propertyId;
    postBackData += ", CountryId :";
    postBackData += countryId;
    postBackData += ", CurrencyId :";
    postBackData += _currencyId;
    postBackData += ", UnitId :";
    postBackData += _unitId;
    postBackData += ", CultureName :'";
    postBackData += getCurrentCulture();
    postBackData += "'}";
    jQuery.ajax({
        type: "POST",
        url: "Home.aspx/getPropertyDetails",
        data: postBackData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(content) {
            displayPropertyDetailImages(content);
            setPropertyDetailInformation(content.d);
            displayPropertyDetail();
        },
        error: function(error) {
            alert(page_ajaxCallError);
        }
    });

    /*window.location = "PropertyDetail.aspx?PropertyId="+propertyId+"&CountryId="+countryId;*/
}

function displayPropertyDetailImages(content) {
    var corouselImages = content.d.PropertyImages;
    var propertyId = content.d.PropertyId;
    var corouselSelector = '#' + propertyId;
    var slideShow = $('#divPropertySlideShow');
    var mainImage = $(slideShow.find('.mainImage'));
    if (corouselImages != null) {
        var imageCount = corouselImages.length;

        slideShow.removeClass('hidden');
        $('#divPropertyDetailNoImg').addClass('hidden');

        //mainImage.attr("src", corouselImages[0].PosterImageUrl);
        mainImage.attr("src", content.d.PrimaryImage);
        if (imageCount > 1) {

            var imgCorousel = slideShow.find(corouselSelector);
            var corouselLength = imgCorousel.length;
            if (corouselLength == 0) {
                slideShow.find('.jcarousel-skin-tango').addClass('hidden');
                var corouselContainer = slideShow.find('.corouselContainer');

                var corouselList = $('<ul id="' + propertyId + '" class="propertyDetailCorousel jcarousel-skin-tango"></ul>');

                var tplCorouselImageTxt = $('#tplCorouselImage').html();
                corouselList.remove('li');
                for (var i = 0; i < imageCount; i++) {
                    var t1 = $.template(tplCorouselImageTxt);
                    corouselList.append(t1, corouselImages[i]);
                }

                corouselContainer.removeClass('hidden');
                corouselContainer.append(corouselList);
                // Initialize the corousel as we have changed the HTML
            }
            else {
                slideShow.find('.jcarousel-skin-tango').addClass('hidden');
                imgCorousel.parents('.jcarousel-skin-tango').removeClass('hidden');
            }
        }
        else {
            slideShow.find('.corouselContainer').addClass('hidden');
        }
    }
    else {
        slideShow.addClass('hidden');
        $('#divPropertyDetailNoImg').removeClass('hidden');
    }
}

function displayPropertyDetail() {

    hideAllScrenes();
    $('#divPropetyDetailContainer').removeClass('hidden');
    var breadcrumbPropertySearch = $('#breadcrumb_PropertySearch');
    $('#breadcrumb_Home').removeClass('hidden');
    breadcrumbPropertySearch.addClass('link');

    if (_isFeaturedProperty == true) {
        breadcrumbPropertySearch.addClass('hidden');
    }
    else {
        breadcrumbPropertySearch.removeClass('hidden');
    }

    propertyDetailCorousel = $('.propertyDetailCorousel');


    initializeCorousel('.propertyDetailCorousel');
};

function setPropertyDetailInformation(PropertyDetailInformation) {


    var propertyData = $('.divPropertyDetailData');
    var stylevalue = "";

    propertyData.find("#detail_Price").html(PropertyDetailInformation.Price);
    propertyData.find("#detail_ListingId").html(PropertyDetailInformation.ListingId);
    propertyData.find("#detail_Address").html(PropertyDetailInformation.Address);
    propertyData.find("#detail_Product").html(PropertyDetailInformation.Product);
    propertyData.find("#detail_Style").html(PropertyDetailInformation.Style);
    propertyData.find("#detail_LivingArea").html(PropertyDetailInformation.LivingArea);
    propertyData.find("#detail_LandArea").html(PropertyDetailInformation.LandArea);
    propertyData.find("#detail_Beds").html(PropertyDetailInformation.BedRooms);
    propertyData.find("#detail_Baths").html(PropertyDetailInformation.BathRooms);
    propertyData.find("#spanPropertyTitle").html(PropertyDetailInformation.PropertyTitle);
    if (PropertyDetailInformation.BedRooms != 0)
        stylevalue = PropertyDetailInformation.BedRooms + " " + page_bedroom + " " + PropertyDetailInformation.Product;
    else
        stylevalue =  PropertyDetailInformation.Product;
    document.getElementById("print_style").value = stylevalue;
    document.getElementById("print_address").value = PropertyDetailInformation.Address;
    document.getElementById("print_refno").value = PropertyDetailInformation.ListingId;
     
   
    propertyData.find("#detail_Description").html(PropertyDetailInformation.Description);
    if (PropertyDetailInformation.VirtualTourUrl != "" && PropertyDetailInformation.VirtualTourUrl != null) {
        var virtualTourContainer = propertyData.find(".detail_virtualTourContainer");
        virtualTourContainer.removeClass('inVisible');
        virtualTourContainer.find('.a_virtualTourUrl').attr('href', PropertyDetailInformation.VirtualTourUrl);
    }
    else {
        var virtualTourContainer = propertyData.find(".detail_virtualTourContainer");
        virtualTourContainer.addClass('inVisible');
        virtualTourContainer.find('.a_virtualTourUrl').attr('href', "#");
    }
    
    var bedroom = propertyData.find("#detailbedroomdesc");
    var bathroom = propertyData.find("#detailbathroomdesc");
    if (PropertyDetailInformation.DetailShow == false) {
        $(bedroom).hide();
        $(bathroom).hide();
    }
    else {
        $(bedroom).show();
        $(bathroom).show();
    }
    

    var agentMembershipId = $("#hdnAgentMembershipId").val();
    var listingMembershipId = PropertyDetailInformation.SalespersonMembershipId;

    if( PropertyDetailInformation.MLSOfficeName == "" )
        propertyData.find("#detail_CourtesyOf").html(PropertyDetailInformation.PropertyAgencyName);
    else
        propertyData.find("#detail_CourtesyOf").html(PropertyDetailInformation.MLSOfficeName);

    propertyData.find("#detail_Latitude").val(PropertyDetailInformation.Latitude);
    propertyData.find("#detail_Longitude").val(PropertyDetailInformation.Longitude);

    displayFeatures('#detail_BuildingFeatures', PropertyDetailInformation.BuildingFeatures);
    displayFeatures('#detail_GroundFeatures', PropertyDetailInformation.GroundFeatures);
    displayFeatures('#detail_NearbyAttractions', PropertyDetailInformation.NearbyAttractions);

    removeMarkers();
    addMarker(PropertyDetailInformation.Latitude, PropertyDetailInformation.Longitude, PropertyDetailInformation.Address);
    centerMap(PropertyDetailInformation.Latitude, PropertyDetailInformation.Longitude);
    $('.detail_contactMe').click(function() {
        var mailText = page_contactProperty.replace("txt_RefNumber", PropertyDetailInformation.ListingId);
        var mailText = mailText.replace("txt_Address", PropertyDetailInformation.Address);
        displayContactForm(mailText);
    });
}

function displayFeatures(containerSelector, featureList) {
    var container = $(containerSelector);
    var block = container.parents('.propertyDetialDataBlock');

    if (featureList == null) {
        block.addClass('hidden');
    }
    else {
        var featureCount = featureList.length;
        container.html("");
        block.removeClass('hidden');

        var spanFeature = $('<div></div>').addClass('clear');
        container.append(spanFeature);

        for (var i = 0; i < featureCount; i++) {
            var spanFeature = $('<span></span>').html(featureList[i]);
            container.append(spanFeature);
        }

        var spanFeature = $('<div></div>').addClass('clear');
        container.append(spanFeature);
    }

}

/*---   Email related Functions     ---*/



function displayContactForm(mailBody) {
    var txtMailBody = $('#txtMailBody');
    if (mailBody == undefined || mailBody == null)
        txtMailBody.val('');
    else
        txtMailBody.val(mailBody);
        
    $find('mdlPopup').show();
}

function displayAgentContactForm(mailBody) {
    var result = page_AgentMailSubject;
   // var result = jQuery("[name$='agentmailSubject']").val();

    result += " " + $('#hdnAgencyinformation').val();
    document.getElementById("agentmailSubject").value = result;
    var txtMailBody = $('#agentTextMailBody');
    if (mailBody == undefined || mailBody == null)
        txtMailBody.val('');
    else
        txtMailBody.val(mailBody);

    $find('mdlPopupMailTo').show();
}


function displayAgencyContactForm(mailBody) {

    var result = jQuery("[name$='agencymailsubject']").val();

    var txtMailBody = $('#agencyTextMessage');
    if (mailBody == undefined || mailBody == null)
        txtMailBody.val('');
    else
        txtMailBody.val(mailBody);

    $find('mdlPopupEmail').show();
}

function sendAgencyMail() {

    $find('mdlPopupEmail').hide();
    var Agencyid = jQuery('#hdnAgencyId').val();
    var AgencyName = jQuery('#hdnAgencyinformation').val();
    var senderName = jQuery('#TextBox2').val();
    var SenderEmail = jQuery('#txtsenderEmail').val();
    var agentEmail = document.getElementById('hdnAgentEmailID').value;

    var Name = page_Name + " :";
    var form = page_Form + " :";
    var poweredby = page_poweredBy + " " + "Proxio";
    var culture = getCurrentCulture();
 

    if (SenderEmail == "") {
        alert(page_alertMessage);
        return;
    }

    var MailBody = jQuery('#agencyTextMessage').val();

    var subject = jQuery('#agencymailsubject').val();

    var data = "{SenderName : '";
    data += senderName;
    data += "', SenderEmail : '";
    data += SenderEmail;
    data += "', agentEmail : '";
    data += agentEmail;
    data += "', Name : '";
    data += Name;
    data += "', From : '";
    data += form;
    data += "', poweredby : '";
    data += poweredby;
    data += "', Culture : '";
    data += culture;      
    data += "', MailSubject : '";
    data += subject;
    data += "', MailBody : '";
    data += MailBody;
    data += "'}";
    jQuery.ajax({
        type: "POST",
        url: "Home.aspx/sendAgencyMail",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {

            finalize(true);
        },
        error: function(error) {

            finalize(false);
        }
    });

}









function sendAgentMail() {

    $find('mdlPopupMailTo').hide();
    var Agencyid = jQuery('#hdnAgencyId').val();
    var AgencyName = jQuery('#hdnAgencyinformation').val();
    var SenderEmail = jQuery('#agentformemail').val();
    if (SenderEmail == "") {
        alert("Please Enter Sender EmailAddress");
        return;
    }
    var ReceVerEmail = jQuery('#agentTomail').val();
    if (ReceVerEmail == "" || ReceVerEmail == "Enter Email Address") {
        alert(page_alertMessage);
        return;
    }
    var culture = getCurrentCulture();
    var Name = page_Name + " :";
    var form = page_Form + " :";
    var poweredby = page_poweredBy + " " + "Proxio";
    var MailBody = jQuery('#agentTextMailBody').val();
    var SenderName = jQuery('#agentName').val();
    var subject = jQuery('#agentmailSubject').val();
    var refno = $("#print_refno").val();
    var address = $("#print_address").val();
    var style = $("#print_style").val();


    var data = "{AgencyId : ";
    data += Agencyid;
    data += ", AgencyName : '";
    data += AgencyName;
    data += "', SenderEmail : '";
    data += SenderEmail;    
    data += "', ReciverEmail : '";
    data += ReceVerEmail;
    data += "', SenderName : '";
    data += SenderName;
    data += "', Culture : '";
    data += culture;
    data += "', Name : '";
    data += Name;
    data += "', From : '";
    data += form;
    data += "', poweredby : '";
    data += poweredby;
    data += "', MailSubject : '";
    data += subject;
    data += "', MailBody : '";
    data += MailBody;
    data += "'}";
    jQuery.ajax({
        type: "POST",
        url: "Home.aspx/sendAgentMail",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {

            finalize(true);
        },
        error: function(error) {

            finalize(false);
        }
    });

}




function sendMail() {
  
    
    $find('mdlPopup').hide();
    $find('popupProcessing').show();
   
    var ListingAgentId = document.getElementById("hdnCurrentPropertyAgentlistingId").value
    var listingType1 = 1;
    var myListing1 = $('#rdbMyListing');
    if (myListing1[0].checked)
        listingType1 = 1;
    else
        listingType1 = 2; 
    var propertyAgentId=  $("#hdnAgentId").val();
    var Agencyid = jQuery('#hdnAgencyId').val();
    var SenderEmail = jQuery('#txtFromEmail').val();
    var MailBody = jQuery('#txtMailBody').val();
    var SenderName = jQuery('#txtSenderName').val();
    var subject = jQuery('#txtSubject').val();
    var culture = getCurrentCulture();

    var data = "{AgencyId : ";
    data += Agencyid;
    data += ", SenderEmail : '";
    data += SenderEmail;
    data += "', SenderName : '";
    data += SenderName;
    data += "', MembershipID : '";
    data += ListingAgentId;
    data += "', ListingType :";
    data += listingType1;
    data += ", Culture : '";
    data += culture;
    data += "', MailSubject : '";
    data += subject;
    data += "', MailBody : '";
    data += MailBody;
    data += "'}";
    jQuery.ajax({
        type: "POST",
        url: "Home.aspx/sendMail",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
        
            finalize(true);
        },
        error: function(error) {
        
            finalize(false);
        }
    });
}

function finalize(status) {
    $find('popupProcessing').hide();
    if (status == true) {
        jQuery('#txtFromEmail').val("");
        jQuery('#txtMailBody').val("");
        jQuery('#txtSubject').val(page_SubjectContent);
        jQuery('#lblMailStatus').text("Mail Successfully sent.");

    }
    else {
        jQuery('#txtFromEmail').val("");
        jQuery('#txtMailBody').val("");
        jQuery('#txtSubject').val("");
        jQuery('#lblMailStatus').text("There was some error in sending mail");
    }
    $find('popupMailStatus').show();
}

/* General Functions */
function getCurrentCulture() {
    return $('#hdnCurrentCulture').val();
}

