﻿var myFavLArr;


String.prototype.replaceAll = function(pcFrom, pcTo) {
    var i = this.indexOf(pcFrom);
    var c = this;
    while (i > -1) {
        c = c.replace(pcFrom, pcTo);
        i = c.indexOf(pcFrom);
    }
    return c;
}


/**
* function to Format a given usa 10 digit phone no(999999999) to (9999-999-999)
* @param {Int} phone -Unformated USA 10 digit Phone no.
*/
function FormatPhone(phone) {
    var result;
    //if phone no given is not of length 10 return without formating it
    if (phone.toString().length != 10)
        result = phone.toString();
    else
        result = phone.toString().substring(0, 3) + '-' + phone.toString().substring(3, 6) + '-' + phone.toString().substring(6, 10);
    return result;
}


/**
* function to decode and return JSON serialzed date format in normal form
* @param {string} value - JSON serialize date
* @return (Date) Returns Normal formated date
*/
function $D(value)
{ return new Date(parseInt(value)); }


/**
* Show the count from the search results on a message balloon
*/
function ShowCount() {
    var $divcount = $('#divcount', mapContext);
    $divcount.html(" <b>" + resultCount + "</b>" + " Properties Found.");
}


/**
* Show or hide the alert warning on message balloon about too many properties
*/
function ShowHideAlert() {
    var $divAlert = $('#divAlert', mapContext);
    var $ddlIPPage = $(".ddlPropertiesPerPage");
    //alert(resultCount);
    if (resultCount == 0) {
        $('#divAlertMsg', $divAlert).html(" No Properties in this area match your search criteria.");
        $divAlert.show();
        $ddlIPPage.hide();
    }
    else if (resultCount > 300) {
        $('#divAlertMsg', $divAlert).html("Too many properties, narrow your search results to less than 300.");
        $divAlert.show();
        $ddlIPPage.hide();

    }
    else {
        //WriteDebug("Trying to hide");
        $divAlert.hide();
        $ddlIPPage.show();
    }
}





/**
* function to get the value of checkbox and other DOM Elements
* @param {string} ControlName -id of the Element
* @param {object} controltype -object used as enum to get type of element eg.Checkbox,Dropdown list
* @return (var) Return bool is contrl type is checkbox otherwise return value of element in String
*/
function GetCheckboxValue(ControlName, controltype) {
    var toReturn;
    if (controltype == ControlType.CheckBox) {
        //toReturn = $($(ControlName, criteriaContext)[0].childNodes[0]).is(":checked"); //deprecated
        toReturn = $(ControlName + ' :checkbox').is(":checked");

    }
    else {
        toReturn = $(ControlName).val();
    }
    return toReturn;

}



/**
* function to check whether a specific element has the given classname applied on it
* @param {object} objElement-DOM Element object
* @param {string} strClass- name of the class to search on Element
* @return (bool) Returns bool value which shows element has the class applied or not
*/
function HasClassName(objElement, strClass) {

    // if there is a class
    if (objElement.className) {

        // the classes are just a space separated list, so first get the list
        var arrList = objElement.className.split(' ');

        // get uppercase class for comparison purposes
        var strClassUpper = strClass.toUpperCase();

        // find all instances and remove them
        for (var i = 0; i < arrList.length; i++) {

            // if class found
            if (arrList[i].toUpperCase() == strClassUpper) {

                // we found it
                return true;

            }

        }

    }

    // if we got here then the class name is not there
    return false;

}


/**
* function to get bounding box in Birds Eye view of map:: TODO:its not giving accurate bounding box
* @param {object} mapDiv-name if div containing map
* @return (object) Returns bounding box
*/
function GetBoundingBoxForBirdEye(mapDiv) {


    var info = "";
    var view = map.GetMapView();
    view = map.GetBirdseyeScene().GetBoundingRectangle();

    //get birds eye scene
    var be = map.GetBirdseyeScene();
    var pixel = be.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());




    // Get the Lat/Long Center of current birds eye view
    var center = be.PixelToLatLong(pixel, map.GetZoomLevel());
    // Convert the BirdseyeScene LatLong to a normal LatLong we can use
    var cLatLng = (new _xy1).Decode(center);




    //get size of map and map div object
    var Mapdiv = document.getElementById(mapDiv);
    var MapHeight = Mapdiv.clientHeight.toString();
    var MapWidth = Mapdiv.clientWidth.toString();


    //get pixels for TopLeft corner using center offset
    var TLxx = pixel.x - Math.floor((MapWidth / 2));
    var TLyy = pixel.y - Math.floor((MapHeight / 2));

    //get pixels for BottomRight corner using center offset
    var BRxx = Math.floor((MapWidth / 2)) + pixel.x;
    var BRyy = Math.floor((MapHeight / 2)) + pixel.y;



    // Get the Lat/Long 
    var TLp = be.PixelToLatLong(new VEPixel(TLxx, TLyy), map.GetZoomLevel());
    // Convert the BirdseyeScene LatLong to a normal LatLong we can use
    var TLLatL = (new _xy1).Decode(TLp);

    // Get the Lat/Long 
    var BRp = be.PixelToLatLong(new VEPixel(BRxx, BRyy), map.GetZoomLevel());
    // Convert the BirdseyeScene LatLong to a normal LatLong we can use
    var BRLatL = (new _xy1).Decode(BRp);





    var ViewNorthLat = TLLatL.Latitude;
    var ViewWestLon = TLLatL.Longitude;

    var ViewSouthLat = BRLatL.Latitude;
    var ViewEastLon = BRLatL.Longitude;

    var TopLeftLatLong = { Latitude: ViewNorthLat, Longitude: ViewWestLon };
    var BottomRightLatLong = { Latitude: ViewSouthLat, Longitude: ViewEastLon };


    return { TopLeftLatLong: TopLeftLatLong, BottomRightLatLong: BottomRightLatLong };

}



/**
* Show or hide the legends window 
*/
function ShowHideLegend(Viewlegend,leftOffset,topOffset) {
    // get whether ViewLegned checkbox is checked
    //var Viewlegend=$(".chkViewLegends :checkbox", mapContext).is(":checked");    

    if (Viewlegend) {
        // if checked get and show the legend div              
        legendleft = mapleft + leftOffset; // moves the div to right side of MAp
        legendtop = maptop + topOffset;
        GetControl(map, "DivShowLegends", legendleft, legendtop)
        //GetControl(map,"DivShowLegends",885,420)
    }
    else {
        document.getElementById('DivShowLegends').style.visibility = 'hidden';
    }

}


/**
* This function helps determine the type of listing.
* @param (object) listing - Listing object
* @return (object) Return object ListingType
*/
function GetTypeForListing(listing) {
    var toReturn;
    if (listing.OpenHouse)
        toReturn = ListingType.OpenHouse;
    else if (listing.isSold)
        toReturn = ListingType.SoldListing;
    else if (IsNewListing(listing))
        toReturn = ListingType.NewListing;
    else if (IsFavoriteListing(listing))
        toReturn = ListingType.Favorite;
    else
        toReturn = ListingType.Default;

    return toReturn
}




/**
* This function helps determine the status of listing for grid.
* @param (object) listing - Listing object
* @return (string) Return status of the listing 
*/
function GetStatusForListing(listing) {
    var toReturn;
    if (listing.OpenHouse)
        toReturn = "Open House";
    else if (listing.isSold)
        toReturn = "Sold";
    else if (IsNewListing(listing))
        toReturn = "New on Market";
    else if (IsFavoriteListing(listing))
        toReturn = "Favorite";
    else
        toReturn = listing.PropertyStatusName;

    return toReturn
}


/**
* This function is used to get image name of the listing source
* @param (object) listing - Listing object
* @return (string) Return name of the image file
*/
function GetMLSImageByMLSID(listing) {
    var mlsid = listing.MlsId2.toString().trim();
    if (mlsid == "1")
        return "NWMLSOListingIcon.gif";
    else
        //return "RMLSOListingIcon.gif";
        return "RMLSListingIconSmall.gif";
}




/**
* Determins if the listing is a new listing based on the date-time listing was added
* @param (object) listing - Listing object
* @return (bool) Return whether a listing is new listing
*/
function IsNewListing(listing) {
    // now calculate dates diffrence
    UniversalDate = listing.ListingAddTime;
    pos = UniversalDate.indexOf('('); // get first occ. of (
    lpos = UniversalDate.lastIndexOf(')'); // get last occ. of )
    ListingDate = UniversalDate.substring(++pos, lpos);

    // convert to int
    ListingAddTime = parseInt(ListingDate);
    dt1 = new Date(); // get current date            
    dt2 = $D(ListingAddTime); // get listing date

    // get days between current and listing is added
    NewPropertyDays = Math.ceil((dt1.getTime() - dt2.getTime()) / (one_day));

    if (NewPropertyDays > 3)
        return false;
    else
        return true;
}


/**
* Determines if the current listing is a favorite for the current user.
* @param (object) listing - Listing object
* @return (bool) Return whether a listing is favorite listing
*/
function IsFavoriteListing(listing) {
    var ListingID = listing.ListingID;

    if (myFavLArr == undefined) {
        myFavLArr = new Array();
        // get values for FavListings from hidden field
        // get all favlistings as string
        var FavhidField = $("#" + hiddenFavListingID, mapContext);
        var FavoriteListings = FavhidField.val();
        var FavListings;
        // means if there is some Favorite listings go
        // split the array then, other wise no 
        if (FavoriteListings != "") {
            FavListings = FavoriteListings.split(";");
        }

        for (var i in FavListings) {
            myFavLArr[FavListings[i]] = FavListings[i];
        }

    }

    if (myFavLArr[ListingID] == undefined)
        return false;
    else
        return true;

}



/**
* Determines the icon to use for a given listing type. 
* (Not to be confused with property type)
* @param (object) listingType - object specifies type(status) of property
* @return (bool) Return icon file name for listing
*/
function GetIconForType(listingType) {
    var toReturn;
    switch (listingType) {
        case ListingType.Default:
            toReturn = "property_icon.gif";
            break;
        case ListingType.NewListing:
            toReturn = "new_property_icon.gif";
            break;
        case ListingType.OpenHouse:
            toReturn = "open_house_icon.gif";
            break;
        case ListingType.SoldListing:
            toReturn = "sold_house_icon.gif";
            break;
        case ListingType.Favorite:
            toReturn = "favorite_icon_26.gif";
            break;
        default:
            toReturn = "property_icon.gif";
    }

    return toReturn
}

function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function() {
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function() {
    return this.strings.join("");
}


function sortByLP(a, b)
{ return a.LPSortOrder - b.LPSortOrder; }


function sortByMLS(a, b)
{ return a.MLSSortOrder - b.MLSSortOrder; }


//used to apply stripes on rows of the map
$.fn.alternateRowColors = function() {
    $('tbody tr:odd', this).removeClass('even').addClass('odd');
    $('tbody tr:even', this).removeClass('odd').addClass('even');
    return this;
};




/**
* Function used to make grid sortable
* this function is purely JQuery code
*/
function MakeListingTableSortable() {
    //WriteDebug("Starting listing grid sortable method");

    $('table.sortable').each(function() {
        var $table = $(this);
        $table.alternateRowColors($table);

        $table.find('th').each(function(column) {
            var findSortKey;
            if ($(this).is('.sort-alpha')) {
                findSortKey = function($cell) {
                    return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
                };
            }
            else if ($(this).is('.sort-numeric')) {
                findSortKey = function($cell) {
                    var key = parseFloat($cell.text().replace(/^[^\d.]*/, ''));
                    return isNaN(key) ? 0 : key;
                };
            }
            else if ($(this).is('.sort-date')) {
                findSortKey = function($cell) {
                    return Date.parse('1 ' + $cell.text());
                };
            }


            if (findSortKey) {
                $(this).addClass('clickable').hover(function() {
                    $(this).addClass('hover');
                }, function() {
                    $(this).removeClass('hover');
                }).click(function() {
                    var newDirection = 1;
                    if ($(this).is('.sorted-asc')) {
                        newDirection = -1;
                    }

                    rows = $table.find('tbody > tr').get();
                    $.each(rows, function(index, row) {
                        row.sortKey =
    findSortKey($(row).children('td').eq(column));
                    });

                    rows.sort(function(a, b) {
                        if (a.sortKey < b.sortKey) return -newDirection;
                        if (a.sortKey > b.sortKey) return newDirection;
                        return 0;
                    });

                    $.each(rows, function(index, row) {
                        $table.children('tbody').append(row);
                        row.sortKey = null;
                    });

                    $table.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
                    var $sortHead = $table.find('th').filter(':nth-child(' + (column + 1) + ')');
                    if (newDirection == 1) {
                        $sortHead.addClass('sorted-asc');
                    }
                    else {
                        $sortHead.addClass('sorted-desc');
                    }

                    $table.find('td').removeClass('sorted')
    .filter(':nth-child(' + (column + 1) + ')')
    .addClass('sorted');
                    $table.alternateRowColors($table);
                    $table.trigger('repaginate');
                });

            }

        });

    });

    //WriteDebug("Completed listing grid sortable method");
}


/**
* Function used to make grid pagenated
* this function is purely JQuery code
*/
function PageListingTable() {

    //WriteDebug("Starting Making listing grid pageable");

    $('table.paginated').each(function() {
        var $gridDiv = $('div#ListingGridContainer');
        var currentPage = 0;
        var $numPerPage = $(".ddlPropertiesPerPage")
        var numPerPage = $numPerPage.val();

        var $table = $(this);

        $table.bind('repaginate', function() {
            $table.find('tbody tr').show()
        .slice(0, currentPage * numPerPage).hide().end()
        .slice((currentPage + 1) * numPerPage).hide().end();
        });

        var numRows = $table.find('tbody tr').length;
        var numPages = Math.ceil(numRows / numPerPage);
        var $pager = $('<div class="pager"></div>');

        for (var page = 0; page < numPages; page++) {
            $('<span class="page-number"><u>' + (page + 1) + '</u> </span>')
        .bind('click', { 'newPage': page }, function(event) {
            currentPage = event.data['newPage'];
            $table.trigger('repaginate');
            $(this).addClass('active').siblings().removeClass('active');
        })
        .appendTo($pager).addClass('clickable');
        }

        $pager.find('span.page-number:first').addClass('active');
        $(".pager", $gridDiv).empty(); //remove previos pager if any
        $pager.insertBefore($table);
        $table.trigger('repaginate');
    });


    //WriteDebug("Completed Making listing grid pageable");
};





/**
* show image popup div when mouse hover on a grid row's property icon
* @param (string) listingImageUrl - listing image url(absolute)
*/
function ShowGridImageRowPopup(listingImageUrl) {
    // Show ballon picture
    var $FloatingDiv = $("#FloatingDiv");
    $FloatingDiv.html("<img src='" + listingImageUrl + "' alt='' width='80'/>");
    ShowContent('FloatingDiv'); return true;
}

/**
* Hide Info Balloon from the map
*/
function HideInfoBox() {
    map.HideInfoBox();
    return true;
}


/**
* to hide row imagepopup in listinggrid
*/
function HideGridImageRowPopup() {
    HideContent('FloatingDiv');
    return true;
}



/**
* Function is used to format an amount in comma formated eg. 123,232,22
* @param (string) amount- unformated amount
* @return (string) Returns comma formated string
*/
function CommaFormatted(amount) {

    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    //	if(d.length < 1) { amount = n; }
    //	else { amount = n + '.' + d; }
    amount = minus + n;
    return amount;
}

/**
* Function is used to format an amount in currency format eg. 123,232,22.00
* @param (string) amount- unformated amount
* @return (string) Returns currency formated string
*/
function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return CommaFormatted(s);
}







// DESGINER NEED TO CHANGE THIS . ADDED TEMPORARY
// TO DO DESGINER NEED TO MAKE FLOATING TD Div to more genric 
// like at public site
var cX = 0; var cY = 0; var rX = 0; var rY = 0;

function UpdateCursorPosition(e) { cX = e.pageX; cY = e.pageY; }

function UpdateCursorPositionDocAll(e) { cX = event.clientX; cY = event.clientY; }

if (document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
    if (self.pageYOffset) {
        rX = self.pageXOffset;
        rY = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        rX = document.documentElement.scrollLeft;
        rY = document.documentElement.scrollTop;
    }
    else if (document.body) {
        rX = document.body.scrollLeft;
        rY = document.body.scrollTop;
    }
    if (document.all) {
        cX += rX;
        cY += rY;
    }
    d.style.left = (cX + 10) + "px";
    d.style.top = (cY + 10) + "px";
}

/**
* Function is general purpose methos used to hide any DOM element
* @param (string) d- id of a DOM element
*/
function HideContent(d) {
    if (d == null || d.length < 1) { return; }
    document.getElementById(d).style.display = "none";
}

/**
* Function is general purpose methos used to show any DOM element
* @param (string) d- id of a DOM element
*/
function ShowContent(d) {
    if (d == null || d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    dd.style.display = "block";
}

/**
* Function is general purpose methos used to toggle visiblity of any DOM element
* @param (string) d- id of a DOM element
*/
function ReverseContentDisplay(d) {
    if (d == null || d.length < 1) { return; }
    var dd = document.getElementById(d);
    AssignPosition(dd);
    if (dd.style.display == "none") { dd.style.display = "block"; }
    else { dd.style.display = "none"; }
}



/**
* function to round nembers
* @param (number) num- actual decimal number
* @param (number) dec- number to round
* @return (number) Return rounded number
*/
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}



/**
* function to add controls to map
* @param (object) myMap- VEmap object
* @param (string) id- id of a DOM element to add
* @param (number) left- left of Map div
* @param (number) top- top of Map div
*/
function GetControl(myMap, id, left, top) {
    // check id of control and Map is not null,
    // then get id of control to findand add to MAp
    if ((id != null) && (myMap != null)) {
        // No Luck with Jquery
        // TO DO Fins way to set Div postioning (left, top) 
        // with Jquery
        var mycontrol = document.getElementById(id);

        myMap.AddControl(mycontrol);
        // set is position
        mycontrol.style.left = left + "px";
        mycontrol.style.top = top + "px";
        mycontrol.style.visibility = "visible";
        mycontrol = null;
    }

}




/**
* function create a custom icon HTML markup to be placed on the map as pushpin icon 
* @param (string) IconPath- icon image file path
* @param (number) counter- number to placed on the icon
*/
function SetCustomShape(IconPath, counter, listingType) {
    var Icon;
    if (listingType == ListingType.OpenHouse)

        Icon = "<div>"+
               "<div style='margin-left:-10px;height:30px;width:25px;clear:both;background-color:Transparent background-repeat:no-repeat; background-image: url(../App_Themes/Default/Images/InteractiveMap/baloon.gif)'>&nbsp; </div>" +
               "<div style='width:25px; z-index:500; overflow:visible;  background-color:Transparent background-repeat:no-repeat; background-image: url(../App_Themes/Default/Images/InteractiveMap/" + IconPath + ")' >" +
               "<div style='font-family:Tahoma; color:white; font-size:7.5pt; height:15px;width:18px;   padding-top:5px; padding-left: 7px;'>" + counter + "</div></div></div>";
    else
        Icon = "<div style='width:25px; z-index:500; overflow:visible;  background-color:Transparent background-repeat:no-repeat; background-image: url(../App_Themes/Default/Images/InteractiveMap/" + IconPath + ")' >" +
               "<div style='font-family:Tahoma; color:white; font-size:7.5pt; height:15px;width:18px;   padding-top:5px; padding-left: 7px;'>" + counter + "</div></div>";

    return Icon;
}
