﻿/// <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();
    });

    $('#searchButton').click(function() {
        _currentScreen = 2;
        _isFeaturedProperty = false;
        $('#breadcrumb_Home').removeClass('hidden');
        $('#breadcrumb_PropertySearch').addClass('hidden');
        //        $('#breadcrumb_PropertyDetail').addClass('hidden');
        showSearchLoadingBar();
        $(".ddPageSize").val('10');
        
        var propertySearchParam = getPropertySearchParam();
        if (propertySearchParam == undefined)
            return;
        showSearchResult();
        initializePagination(propertySearchParam);
    });
    
    $('.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");
}

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 page;
var pageInitializedCalled = false;
function initializePagination(propertySearchParam) {
    if (!pageInitializedCalled) {
       page = new Pager();
   }
   page.initialize(propertySearchParam, pageInitializedCalled);
   pageInitializedCalled = true;
};

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 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);
        var mailText = mailText.replace("txt_Address", address);

        displayContactForm(mailText);
    });
}

function updateSearchResults(searchResults) {
    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 = "http://www.proxiopro.com/proxioprosearch/Images/NoImage.png";
        }

        var address = result.AddressLine1 + "<br />" + result.AddressLine2;
        addMarker(result.Latitude, result.Longitude, address);

        var t = $.template(tplSearchResultTxt);
        if (result.VirtualTourUrl == "") {
            result.VirtualTourClass = "inVisible";
        }        
        
        SearchResultContainer.append(t, result);
    }
};

function getPropertySearchParam() {
    var ddCountry = $("[name$='ddCountry']");
    var countryId = ddCountry.val();
    if (countryId == -1 || countryId == undefined) {
        alert(page_pleaseSelectCountry);
        ddCountry.focus();
        return;
    }
    var ddRegion = jQuery("[name$='ddState']");
    var regionId = ddRegion.val();
    var ddCity = jQuery("[name$='ddCity']");
    var cityId = ddCity.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();
    _currencyId = jQuery("[name$='ddCurrency']").find('option:selected').val();
    _unitId = jQuery("[name$='ddAreaUnit']").find('option:selected').val();
    
    var listingType = 1;
    var myListing = $('#rdbMyListing');
    if( myListing[0].checked )
        listingType = 1;
    else
        listingType = 2; 
    


    if ((minPrice == null) || (minPrice.length == 0)) {
        minPrice = 0;
    }
    if ((maxPrice == null) || (maxPrice.length == 0)) {
        maxPrice = 0;
    }

    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());

    var listingAgentId = $("#hdnAgentId").val();
    var officeId = $("#hdnOfficeId").val();
    var officeType = $("#hdnOfficeType").val();

    var propertySearchParam = "{ListingAgentId: ";
    propertySearchParam += listingAgentId;
    propertySearchParam += ", ListingOfficeId: ";
    propertySearchParam += officeId;
    propertySearchParam += ", OfficeType: '";
    propertySearchParam += officeType;
    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) {

    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: "Default.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);
        }
    });
}

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');

    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);
   
    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);
    }
    

    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 sendMail() {

    
    $find('mdlPopup').hide();
    $find('popupProcessing').show();

    var AgentId = jQuery('#hdnAgentId').val();
    var SenderEmail = jQuery('#txtFromEmail').val();
    var MailBody = jQuery('#txtMailBody').val();
    var SenderName = jQuery('#txtSenderName').val();
    var subject = jQuery('#txtSubject').val();
    subject = GetSafeString(subject);
    
    MailBody= GetSafeString(MailBody);
    var data = "{AgentId : ";
    data += AgentId;
    data += ", SenderEmail : '";
    data += SenderEmail;
    data += "', SenderName : '";
    data += SenderName;
    data += "', MailSubject : '";
    data += subject;
    data += "', MailBody : '";
    data += MailBody;
    data += "'}";
    jQuery.ajax({
        type: "POST",
        url: "Default.aspx/sendMail",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
        
            finalize(true);
        },
        error: function(error) {
        
            finalize(false);
        }
    });
}

function GetSafeString(str) {
/**
    * First step in the safety evaluation.  Regex used to replace all escape
    * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character).
    *
    * @property _ESCAPES
    * @type {RegExp}
    * @static
    * @private
    */
   var  _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/;

    /**
    * Second step in the safety evaluation.  Regex used to replace all simple
    * values with ']' characters.
    *
    * @property _VALUES
    * @type {RegExp}
    * @static
    * @private
    */
   var _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/;
    
     /**
    * Third step in the safety evaluation.  Regex used to remove all open
    * square brackets following a colon, comma, or at the beginning of the
    * string.
    *
    * @property _BRACKETS
    * @type {RegExp}
    * @static
    * @private
    */
   _BRACKETS = /(?:^|:|,)(?:\s*\[)+/;

     /**
    * Final step in the safety evaluation.  Regex used to test the string left
    * after all previous replacements for invalid characters.
    *
    * @property _UNSAFE
    * @type {RegExp}
    * @static
    * @private
    */
    var _UNSAFE = /^[\],:{}\s]*$/;


    /* Variables used by stringify */

    /**
    * Regex used to replace special characters in strings for JSON
    * stringification.
    *
    * @property _SPECIAL_CHARS
    * @type {RegExp}
    * @static
    * @private
    */
    var _SPECIAL_CHARS = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/;

    /**
    * Character substitution map for common escapes and special characters.
    *
    * @property _CHARS
    * @type {Object}
    * @static
    * @private
    */
    var _CHARS = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    };
    
    str= str.replace(_ESCAPES, '@').replace(_VALUES, ']').replace(_BRACKETS, '').replace("'","\\'");
    return str;
}

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();
}
